home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2002 November / CD 1 / APC0211D1.ISO / workshop / prog / files / ActivePerl-5.6.1.633-MSWin32.msi / _5a85b816572845bbf411024e80b716b4 < prev    next >
Encoding:
Text File  |  2001-08-20  |  116.0 KB  |  3,822 lines

  1.  
  2. require 5;
  3. # Time-stamp: "2001-03-10 22:42:16 MST"
  4. package HTML::Element;
  5. # TODO: add pre-content-fixer, like from Pod::HTML2Pod?
  6. # TODO: make extract_links do the right thing with forms with no action param ?
  7. # TODO: add 'are_element_identical' method ?
  8. # TODO: add 'are_content_identical' method ?
  9. # TODO: maybe alias ->destroy to ->delete, because I keep mixing them up ?
  10. # TODO: maybe reorganize the docs some time?
  11.  
  12. # TODO: $node->rebless( what_class )
  13. #        and/or  $node->rebless_down( what_class ) # recurses
  14.  
  15. =head1 NAME
  16.  
  17. HTML::Element - Class for objects that represent HTML elements
  18.  
  19. =head1 SYNOPSIS
  20.  
  21.   use HTML::Element;
  22.   $a = HTML::Element->new('a', href => 'http://www.perl.com/');
  23.   $a->push_content("The Perl Homepage");
  24.  
  25.   $tag = $a->tag;
  26.   print "$tag starts out as:",  $a->starttag, "\n";
  27.   print "$tag ends as:",  $a->endtag, "\n";
  28.   print "$tag\'s href attribute is: ", $a->attr('href'), "\n";
  29.  
  30.   $links_r = $a->extract_links();
  31.   print "Hey, I found ", scalar(@$links_r), " links.\n";
  32.   
  33.   print "And that, as HTML, is: ", $a->as_HTML, "\n";
  34.   $a = $a->delete;
  35.  
  36. =head1 DESCRIPTION
  37.  
  38. (This class is part of the L<HTML::Tree|HTML::Tree> dist.)
  39.  
  40. Objects of the HTML::Element class can be used to represent elements
  41. of HTML document trees.  These objects have attributes, notably attributes that
  42. designates each element's parent and content.  The content is an array
  43. of text segments and other HTML::Element objects.  A tree with HTML::Element
  44. objects as nodes can represent the syntax tree for a HTML document.
  45.  
  46. =head1 HOW WE REPRESENT TREES
  47.  
  48. It may occur to you to wonder what exactly a "tree" is, and how
  49. it's represented in memory.  Consider this HTML document:
  50.  
  51.   <html lang='en-US'>
  52.     <head>
  53.       <title>Stuff</title>
  54.       <meta name='author' content='Jojo'>
  55.     </head>
  56.     <body>
  57.      <h1>I like potatoes!</h1>
  58.     </body>
  59.   </html>
  60.  
  61. Building a syntax tree out of it makes a tree-structure in memory
  62. that could be diagrammed as:
  63.  
  64.                      html (lang='en-US')
  65.                       / \
  66.                     /     \
  67.                   /         \
  68.                 head        body
  69.                /\               \
  70.              /    \               \
  71.            /        \               \
  72.          title     meta              h1
  73.           |       (name='author',     |
  74.        "Stuff"    content='Jojo')    "I like potatoes"
  75.  
  76. This is the traditional way to diagram a tree, with the "root" at the
  77. top, and it's this kind of diagram that people have in mind when they
  78. say, for example, that "the meta element is under the head element
  79. instead of under the body element".  (The same is also said with
  80. "inside" instead of "under" -- the use of "inside" makes more sense
  81. when you're looking at the HTML source.)
  82.  
  83. Another way to represent the above tree is with indenting:
  84.  
  85.   html (attributes: lang='en-US')
  86.     head
  87.       title
  88.         "Stuff"
  89.       meta (attributes: name='author' content='Jojo')
  90.     body
  91.       h1
  92.         "I like potatoes"
  93.  
  94. Incidentally, diagramming with indenting works much better for very
  95. large trees, and is easier for a program to generate.  The $tree->dump
  96. method uses indentation just that way.
  97.  
  98. However you diagram the tree, it's stored the same in memory -- it's a
  99. network of objects, each of which has attributes like so:
  100.  
  101.   element #1:  _tag: 'html'
  102.                _parent: none
  103.                _content: [element #2, element #5]
  104.                lang: 'en-US'
  105.  
  106.   element #2:  _tag: 'head'
  107.                _parent: element #1
  108.                _content: [element #3, element #4]
  109.  
  110.   element #3:  _tag: 'title'
  111.                _parent: element #2
  112.                _content: [text segment "Stuff"]
  113.  
  114.   element #4   _tag: 'meta'
  115.                _parent: element #2
  116.                _content: none
  117.                name: author
  118.                content: Jojo
  119.  
  120.   element #5   _tag: 'body'
  121.                _parent: element #1
  122.                _content: [element #6]
  123.  
  124.   element #6   _tag: 'h1'
  125.                _parent: element #5
  126.                _content: [text segment "I like potatoes"]
  127.  
  128. The "treeness" of the tree-structure that these elements comprise is
  129. not an aspect of any particular object, but is emergent from the
  130. relatedness attributes (_parent and _content) of these element-objects
  131. and from how you use them to get from element to element.
  132.  
  133. While you could access the content of a tree by writing code that says
  134. "access the 'src' attribute of the root's I<first> child's I<seventh>
  135. child's I<third> child", you're more likely to have to scan the contents
  136. of a tree, looking for whatever nodes, or kinds of nodes, you want to
  137. do something with.  The most straightforward way to look over a tree
  138. is to "traverse" it; an HTML::Element method ($h->traverse) is
  139. provided for this purpose; and several other HTML::Element methods are
  140. based on it.
  141.  
  142. (For everything you ever wanted to know about trees, and then some,
  143. see Niklaus Wirth's I<Algorithms + Data Structures = Programs> or
  144. Donald Knuth's I<The Art of Computer Programming, Volume 1>.)
  145.  
  146. =cut
  147.  
  148.  
  149. use strict;
  150. use Carp ();
  151. use HTML::Entities ();
  152. use HTML::Tagset ();
  153. use integer; # vroom vroom!
  154.  
  155. use vars qw($VERSION $html_uc $Debug $ID_COUNTER %list_type_to_sub);
  156.  
  157. $VERSION = '3.09';
  158. $Debug = 0 unless defined $Debug;
  159. sub Version { $VERSION; }
  160.  
  161. my $nillio = [];
  162.  
  163. *HTML::Element::emptyElement = \%HTML::Tagset::emptyElement; # legacy
  164. *HTML::Element::optionalEndTag = \%HTML::Tagset::optionalEndTag; # legacy
  165. *HTML::Element::linkElements = \%HTML::Tagset::linkElements; # legacy
  166. *HTML::Element::boolean_attr = \%HTML::Tagset::boolean_attr; # legacy
  167. *HTML::Element::canTighten = \%HTML::Tagset::canTighten; # legacy
  168.  
  169. # Constants for signalling back to the traverser:
  170. my $travsignal_package = __PACKAGE__ . '::_travsignal';
  171. my(
  172.   $ABORT, $PRUNE, $PRUNE_SOFTLY, $OK, $PRUNE_UP
  173. ) =
  174.   map
  175.    {my $x = $_ ; bless \$x, $travsignal_package;}
  176.    qw(
  177.      ABORT  PRUNE   PRUNE_SOFTLY   OK   PRUNE_UP
  178.    )
  179. ;
  180. sub ABORT           () {$ABORT}
  181. sub PRUNE           () {$PRUNE}
  182. sub PRUNE_SOFTLY    () {$PRUNE_SOFTLY}
  183. sub OK              () {$OK}
  184. sub PRUNE_UP        () {$PRUNE_UP}
  185.  
  186. $html_uc = 0;
  187. # set to 1 if you want tag and attribute names from starttag and endtag
  188. #  to be uc'd
  189.  
  190. # Elements that does not have corresponding end tags (i.e. are empty)
  191.  
  192. #==========================================================================
  193.  
  194.  
  195. =head1 BASIC METHODS
  196.  
  197. =over 4
  198.  
  199. =item $h = HTML::Element->new('tag', 'attrname' => 'value', ... )
  200.  
  201. This constructor method returns a new HTML::Element object.  The tag
  202. name is a required argument; it will be forced to lowercase.
  203. Optionally, you can specify other initial attributes at object
  204. creation time.
  205.  
  206. =cut
  207.  
  208. #
  209. # An HTML::Element is represented by blessed hash reference, much like
  210. # Tree::DAG_Node objects.  Key-names not starting with '_' are reserved
  211. # for the SGML attributes of the element.
  212. # The following special keys are used:
  213. #
  214. #    '_tag':    The tag name (i.e., the generic identifier)
  215. #    '_parent': A reference to the HTML::Element above (when forming a tree)
  216. #    '_pos':    The current position (a reference to a HTML::Element) is
  217. #               where inserts will be placed (look at the insert_element
  218. #               method)  If not set, the implicit value is the object itself.
  219. #    '_content': A ref to an array of nodes under this.
  220. #                It might not be set.
  221. #
  222. # Example: <img src="gisle.jpg" alt="Gisle's photo"> is represented like this:
  223. #
  224. #  bless {
  225. #     _tag => 'img',
  226. #     src  => 'gisle.jpg',
  227. #     alt  => "Gisle's photo",
  228. #  }, 'HTML::Element';
  229. #
  230.  
  231. sub new
  232. {
  233.     my $class = shift;
  234.     $class = ref($class) || $class;
  235.  
  236.     my $tag   = shift;
  237.     Carp::croak("No tagname") unless defined $tag and length $tag;
  238.     my $self  = bless { _tag => scalar($class->_fold_case($tag)) }, $class;
  239.     my($attr, $val);
  240.     while (($attr, $val) = splice(@_, 0, 2)) {
  241.         $val = $attr unless defined $val;
  242.         $self->{$class->_fold_case($attr)} = $val;
  243.     }
  244.     if ($tag eq 'html') {
  245.         $self->{'_pos'} = undef;
  246.     }
  247.     $self;
  248. }
  249.  
  250.  
  251. =item $h->attr('attr') or $h->attr('attr', 'value')
  252.  
  253. Returns (optionally sets) the value of the given attribute of $h.  The
  254. attribute name (but not the value, if provided) is forced to
  255. lowercase.  If trying to read the value of an attribute not present
  256. for this element, the return value is undef.
  257. If setting a new value, the old value of that attribute is
  258. returned.
  259.  
  260. If methods are provided for accessing an attribute (like $h->tag for
  261. "_tag", $h->content_list, etc. below), use those instead of calling
  262. attr $h->attr, whether for reading or setting.
  263.  
  264. Note that setting an attribute to undef (as opposed to "", the empty
  265. string) actually deletes the attribute.
  266.  
  267. =cut
  268.  
  269. sub attr
  270. {
  271.     my $self = shift;
  272.     my $attr = scalar($self->_fold_case(shift));
  273.     if (@_) {  # set
  274.         if(defined $_[0]) {
  275.             my $old = $self->{$attr};
  276.             $self->{$attr} = $_[0];
  277.             return $old;
  278.         } else {  # delete, actually
  279.             return delete $self->{$attr};
  280.         }
  281.     } else {   # get
  282.         return $self->{$attr};
  283.     }
  284. }
  285.  
  286.  
  287. =item $h->tag() or $h->tag('tagname')
  288.  
  289. Returns (optionally sets) the tag name (also known as the generic
  290. identifier) for the element $h.  In setting, the tag name is always
  291. converted to lower case.
  292.  
  293. There are four kinds of "pseudo-elements" that show up as
  294. HTML::Element objects:
  295.  
  296. =over
  297.  
  298. =item Comment pseudo-elements
  299.  
  300. These are element objects with a C<$h-E<gt>tag> value of "~comment",
  301. and the content of the comment is stored in the "text" attribute
  302. (C<$h-E<gt>attr("text")>).  For example, parsing this code with
  303. HTML::TreeBuilder...
  304.  
  305.   <!-- I like Pie.
  306.      Pie is good
  307.   -->
  308.  
  309. produces an HTML::Element object with these attributes:
  310.  
  311.   "_tag",
  312.   "~comment",
  313.   "text",
  314.   " I like Pie.\n     Pie is good\n  "
  315.  
  316. =item Declaration pseudo-elements
  317.  
  318. Declarations (rarely encountered) are represented as HTML::Element
  319. objects with a tag name of "~declaration", and content in the "text"
  320. attribute.  For example, this:
  321.  
  322.   <!DOCTYPE foo>
  323.  
  324. produces an element whose attributes include:
  325.  
  326.   "_tag", "~declaration", "text", "DOCTYPE foo"
  327.  
  328. =item Processing instruction pseudo-elements
  329.  
  330. PIs (rarely encountered) are represented as HTML::Element objects with
  331. a tag name of "~pi", and content in the "text" attribute.  For
  332. example, this:
  333.  
  334.   <?stuff foo?>
  335.  
  336. produces an element whose attributes include:
  337.  
  338.   "_tag", "~pi", "text", "stuff foo?"
  339.  
  340. (assuming a recent version of HTML::Parser)
  341.  
  342. =item ~literal pseudo-elements
  343.  
  344. These objects are not currently produced by HTML::TreeBuilder, but can
  345. be used to represent a "super-literal" -- i.e., a literal you want to
  346. be immune from escaping.  (Yes, I just made that term up.)
  347.  
  348. That is, this is useful if you want to insert code into a tree that
  349. you plan to dump out with C<as_HTML>, where you want, for some reason,
  350. to suppress C<as_HTML>'s normal behavior of amp-quoting text segments.
  351.  
  352. For expample, this:
  353.  
  354.   my $literal = HTML::Element->new('~literal',
  355.     'text' => 'x < 4 & y > 7'
  356.   );
  357.   my $span = HTML::Element->new('span');
  358.   $span->push_content($literal);
  359.   print $span->as_HTML;
  360.  
  361. prints this:
  362.  
  363.   <span>x < 4 & y > 7</span>
  364.  
  365. Whereas this:
  366.  
  367.   my $span = HTML::Element->new('span');
  368.   $span->push_content('x < 4 & y > 7');
  369.     # normal text segment
  370.   print $span->as_HTML;
  371.  
  372. prints this:
  373.  
  374.   <span>x < 4 & y > 7</span>
  375.  
  376. Unless you're inserting lots of pre-cooked code into existing trees,
  377. and dumping them out again, it's not likely that you'll find
  378. C<~literal> pseudo-elements useful.
  379.  
  380. =back
  381.  
  382. =cut
  383.  
  384. sub tag
  385. {
  386.     my $self = shift;
  387.     if (@_) { # set
  388.     #print "SET\n";
  389.         $self->{'_tag'} = $self->_fold_case($_[0]);
  390.     } else { # get
  391.     #print "GET\n";
  392.         $self->{'_tag'};
  393.     }
  394. }
  395.  
  396.  
  397. =item $h->parent() or $h->parent($new_parent)
  398.  
  399. Returns (optionally sets) the parent for this element.
  400. The parent should either be undef, or should be another element.
  401.  
  402. You B<should not> use this to directly set the parent of an element.
  403. Instead use any of the other methods under "Structure-Modifying
  404. Methods", below.
  405.  
  406. Note that not($h->parent) is a simple test for whether $h is the
  407. root of its subtree.
  408.  
  409. =cut
  410.  
  411. sub parent
  412. {
  413.     my $self = shift;
  414.     if (@_) { # set
  415.         Carp::croak "an element can't be made its own parent"
  416.          if defined $_[0] and ref $_[0] and $self eq $_[0]; # sanity
  417.         $self->{'_parent'} = $_[0];
  418.     } else {
  419.         $self->{'_parent'}; # get
  420.     }
  421. }
  422.  
  423.  
  424. =item $h->content_list()
  425.  
  426. Returns a list representing the content of this element -- i.e., what
  427. nodes (elements or text segments) are inside/under this element. (Note
  428. that this may be an empty list.)
  429.  
  430. In a scalar context, this returns the count of the items,
  431. as you may expect.
  432.  
  433. =cut
  434.  
  435. sub content_list
  436. {
  437.     return
  438.       wantarray ?        @{shift->{'_content'} || return()}
  439.                 : scalar @{shift->{'_content'} || return 0};
  440. }
  441.  
  442.  
  443.  
  444. =item $h->content()
  445.  
  446. This somewhat deprecated method returns the content of this element;
  447. but unlike content_list, this returns either undef (which you should
  448. understand to mean no content), or a I<reference to the array> of
  449. content items, each of which is either a text segment (a string, i.e.,
  450. a defined non-reference scalar value), or an HTML::Element object.
  451. Note that even if an arrayref is returned, it may be a reference to an
  452. empty array.
  453.  
  454. While older code should feel free to continue to use $h->content,
  455. new code should use $h->content_list in almost all conceivable
  456. cases.  It is my experience that in most cases this leads to simpler
  457. code anyway, since it means one can say:
  458.  
  459.   @children = $h->content_list;
  460.  
  461. instead of the inelegant:
  462.  
  463.   @children = @{$h->content || []};
  464.  
  465. If you do use $h->content (or $h->content_array_ref), you should not
  466. use the reference returned by it (assuming it returned a reference,
  467. and not undef) to directly set or change the content of an element or
  468. text segment!  Instead use C<content_refs_list> or any of the other
  469. methods under "Structure-Modifying Methods", below.
  470.  
  471. =cut
  472.  
  473. # a read-only method!  can't say $h->content( [] )!
  474. sub content
  475. {
  476.     shift->{'_content'};
  477. }
  478.  
  479.  
  480. =item $h->content_array_ref()
  481.  
  482. This is like C<content> (with all its caveats and deprecations) except
  483. that it is guaranteed to return an array reference.  That is, if the
  484. given node has no C<_content> attribute, the C<content> method would
  485. return that undef, but C<content_array_ref> would set the given node's
  486. C<_content> value to C<[]> (a reference to a new, empty array), and
  487. return that.
  488.  
  489. =cut
  490.  
  491. sub content_array_ref {
  492.   shift->{'_content'} ||= [];
  493. }
  494.  
  495.  
  496. =item $h->content_refs_list
  497.  
  498. This returns a list of scalar references to each element of $h's
  499. content list.  This is useful in case you want to in-place edit any
  500. large text segments without having to get a copy of the current value
  501. of that segment value, modify that copy, then use the
  502. C<splice_content> to replace the old with the new.  Instead, here you
  503. can in-place edit:
  504.  
  505.   foreach my $item_r ($h->content_refs_list) {
  506.     next if ref $$item_r;
  507.     $$item_r =~ s/honour/honor/g;
  508.   }
  509.  
  510. You I<could> currently achieve the same affect with:
  511.  
  512.   foreach my $item (@{ $h->content_array_ref }) {
  513.    # deprecated!
  514.     next if ref $item;
  515.     $item =~ s/honour/honor/g;
  516.   }
  517.  
  518. ...except that using the return value of $h->content or
  519. $h->content_array_ref to do that is deprecated, and just might stop
  520. working in the future.
  521.  
  522. =cut
  523.  
  524. sub content_refs_list {
  525.   \( @{ shift->{'_content'} || return() } );
  526. }
  527.  
  528.  
  529. =item $h->implicit() or $h->implicit($bool)
  530.  
  531. Returns (optionally sets) the "_implicit" attribute.  This attribute is
  532. a flag that's used for indicating that the element was not originally
  533. present in the source, but was added to the parse tree (by
  534. HTML::TreeBuilder, for example) in order to conform to the rules of
  535. HTML structure.
  536.  
  537. =cut
  538.  
  539. sub implicit
  540. {
  541.     shift->attr('_implicit', @_);
  542. }
  543.  
  544.  
  545.  
  546. =item $h->pos() or $h->pos($element)
  547.  
  548. Returns (and optionally sets) the "_pos" (for "current I<pos>ition")
  549. pointer of $h.
  550. This attribute is a pointer used during some parsing operations,
  551. whose value is whatever HTML::Element element at or under $h is
  552. currently "open", where $h->insert_element(NEW) will actually insert a
  553. new element.
  554.  
  555. (This has nothing to do with the Perl function called "pos", for
  556. controlling where regular expression matching starts.)
  557.  
  558. If you set $h->pos($element), be sure that $element is either $h, or
  559. an element under $h.
  560.  
  561. If you've been modifying the tree under $h and are
  562. no longer sure $h->pos is valid, you can enforce validity with:
  563.  
  564.     $h->pos(undef) unless $h->pos->is_inside($h);
  565.  
  566. =cut
  567.  
  568. sub pos
  569. {
  570.     my $self = shift;
  571.     my $pos = $self->{'_pos'};
  572.     if (@_) {  # set
  573.         if(defined $_[0] and $_[0] ne $self) {
  574.           $self->{'_pos'} = $_[0]; # means that element
  575.         } else {
  576.           $self->{'_pos'} = undef; # means $self
  577.         }
  578.     }
  579.     return $pos if defined($pos);
  580.     $self;
  581. }
  582.  
  583.  
  584. =item $h->all_attr()
  585.  
  586. Returns all this element's attributes and values, as key-value pairs.
  587. This will include any "internal" attributes (i.e., ones not present
  588. in the original element, and which will not be represented if/when you
  589. call $h->as_HTML).  Internal attributes are distinguished by the fact
  590. that the first character of their key (not value! key!) is an
  591. underscore ("_").
  592.  
  593. Example output of C<$h-E<gt>all_attr()> :
  594. C<'_parent', >I<[object_value]>C< , '_tag', 'em', 'lang', 'en-US',
  595. '_content', >I<[array-ref value]>.
  596.  
  597. =item $h->all_attr_names()
  598.  
  599. Like all_attr, but only returns the names of the attributes.
  600.  
  601. Example output of C<$h-E<gt>all_attr()> :
  602. C<'_parent', '_tag', 'lang', '_content', >.
  603.  
  604. =cut
  605.  
  606. sub all_attr {
  607.   return %{$_[0]};
  608.   # Yes, trivial.  But no other way for the user to do the same
  609.   #  without breaking encapsulation.
  610.   # And if our object representation changes, this method's behavior
  611.   #  should stay the same.
  612. }
  613.  
  614. sub all_attr_names {
  615.   return keys %{$_[0]};
  616. }
  617.  
  618.  
  619. =item $h->all_external_attr()
  620.  
  621. Like C<all_attr>, except that internal attributes are not present.
  622.  
  623. =item $h->all_external_attr_names()
  624.  
  625. Like C<all_external_attr_names>, except that internal attributes' names
  626. are not present.
  627.  
  628. =cut
  629.  
  630. sub all_external_attr {
  631.   my $self = $_[0];
  632.   return
  633.     map(
  634.         (length($_) && substr($_,0,1) eq '_') ? () : ($_, $self->{$_}),
  635.         keys %$self
  636.        );
  637. }
  638.  
  639. sub all_external_attr_names {
  640.   return
  641.     grep
  642.       !(length($_) && substr($_,0,1) eq '_'),
  643.       keys %{$_[0]}
  644.   ;
  645. }
  646.  
  647.  
  648.  
  649. =item $h->id() or $h->id($string)
  650.  
  651. Returns (optionally sets to C<$string>) the "id" attribute.
  652. C<$h-E<gt>id(undef)> deletes the "id" attribute.
  653.  
  654. =cut
  655.  
  656. sub id {
  657.   if(@_ == 1) {
  658.     return $_[0]{'id'};
  659.   } elsif(@_ == 2) {
  660.     if(defined $_[1]) {
  661.       return $_[0]{'id'} = $_[1];
  662.     } else {
  663.       return delete $_[0]{'id'};
  664.     }
  665.   } else {
  666.     Carp::croak '$node->id can\'t take ' . scalar(@_) . ' parameters!';
  667.   }
  668. }
  669.  
  670.  
  671. =item $h->idf() or $h->idf($string)
  672.  
  673. Just like the C<id> method, except that if you call C<$h->idf()> and
  674. no "id" attribute is defined for this element, then it's set to a
  675. likely-to-be-unique value, and returned.  (The "f" is for "force".)
  676.  
  677. =cut
  678.  
  679. sub _gensym {
  680.   unless(defined $ID_COUNTER) {
  681.     # start it out...
  682.     $ID_COUNTER = sprintf('%04x', rand(0x1000));
  683.     $ID_COUNTER =~ tr<0-9a-f><J-NP-Z>; # yes, skip letter "oh"
  684.     $ID_COUNTER .= '00000';
  685.   }
  686.   ++$ID_COUNTER;
  687. }
  688.  
  689. sub idf {
  690.   if(@_ == 1) {
  691.     my $x;
  692.     if(defined($x = $_[0]{'id'}) and length $x) {
  693.       return $x;
  694.     } else {
  695.       return $_[0]{'id'} = _gensym();
  696.     }
  697.   } elsif(@_ == 2) {
  698.     if(defined $_[1]) {
  699.       return $_[0]{'id'} = $_[1];
  700.     } else {
  701.       return delete $_[0]{'id'};
  702.     }
  703.   } else {
  704.     Carp::croak '$node->idf can\'t take ' . scalar(@_) . ' parameters!';
  705.   }
  706. }
  707.  
  708. #==========================================================================
  709.  
  710. =back
  711.  
  712. =head1 STRUCTURE-MODIFYING METHODS
  713.  
  714. These methods are provided for modifying the content of trees
  715. by adding or changing nodes as parents or children of other nodes.
  716.  
  717. =over 4
  718.  
  719. =item $h->push_content($element_or_text, ...)
  720.  
  721. Adds the specified items to the I<end> of the content list of the
  722. element $h.  The items of content to be added should each be either a
  723. text segment (a string), an HTML::Element object, or an arrayref.
  724. Arrayrefs are fed thru C<$h-E<gt>new_from_lol(that_arrayref)> to
  725. convert them into elements, before being added to the content
  726. list of $h.  This means you can say things concise things like:
  727.  
  728.   $body->push_content(
  729.     ['br'],
  730.     ['ul',
  731.       map ['li', $_]
  732.       qw(Peaches Apples Pears Mangos)
  733.     ]
  734.   );
  735.  
  736. See C<new_from_lol> method's documentation, far below, for more
  737. explanation.
  738.  
  739. The push_content method will try to consolidate adjacent text segments
  740. while adding to the content list.  That's to say, if $h's content_list is
  741.  
  742.   ('foo bar ', $some_node, 'baz!')
  743.  
  744. and you call
  745.  
  746.    $h->push_content('quack?');
  747.  
  748. then the resulting content list will be this:
  749.  
  750.   ('foo bar ', $some_node, 'baz!quack?')
  751.  
  752. and not this:
  753.  
  754.   ('foo bar ', $some_node, 'baz!', 'quack?')
  755.  
  756. If that latter is what you want, you'll have to override the
  757. feature of consolidating text by using splice_content,
  758. as in:
  759.  
  760.   $h->splice_content(scalar($h->content_list),0,'quack?');
  761.  
  762. Similarly, if you wanted to add 'Skronk' to the beginning of
  763. the content list, calling this:
  764.  
  765.    $h->unshift_content('Skronk');
  766.  
  767. then the resulting content list will be this:
  768.  
  769.   ('Skronkfoo bar ', $some_node, 'baz!')
  770.  
  771. and not this:
  772.  
  773.   ('Skronk', 'foo bar ', $some_node, 'baz!')
  774.  
  775. What you'd to do get the latter is:
  776.  
  777.   $h->splice_content(0,0,'Skronk');
  778.  
  779. =cut
  780.  
  781. sub push_content
  782. {
  783.     my $self = shift;
  784.     return $self unless @_;
  785.  
  786.     my $content = ($self->{'_content'} ||= []);
  787.     for (@_) {
  788.         if (ref($_) eq 'ARRAY') {
  789.             # magically call new_from_lol
  790.             push @$content, $self->new_from_lol($_);
  791.         $content->[-1]->{'_parent'} = $self;
  792.         } elsif(ref($_)) {  # insert an element
  793.             $_->detach if $_->{'_parent'};
  794.             $_->{'_parent'} = $self;
  795.             push(@$content, $_);
  796.         } else {  # insert text segment
  797.             if (@$content && !ref $content->[-1]) {
  798.                 # last content element is also text segment -- append
  799.                 $content->[-1] .= $_;
  800.             } else {
  801.                 push(@$content, $_);
  802.             }
  803.         }
  804.     }
  805.     $self;
  806. }
  807.  
  808.  
  809. =item $h->unshift_content($element_or_text, ...)
  810.  
  811. Just like C<push_content>, but adds to the I<beginning> of the $h
  812. element's content list.
  813.  
  814. The items of content to be added should each be
  815. either a text segment (a string), an HTML::Element object, or
  816. an arrayref (which is fed thru C<new_from_lol>).
  817.  
  818. The unshift_content method will try to consolidate adjacent text segments
  819. while adding to the content list.  See above for a discussion of this.
  820.  
  821. =cut
  822.  
  823. sub unshift_content
  824. {
  825.     my $self = shift;
  826.     return $self unless @_;
  827.  
  828.     my $content = ($self->{'_content'} ||= []);
  829.     for (reverse @_) { # so they get added in the order specified
  830.         if (ref($_) eq 'ARRAY') {
  831.             # magically call new_from_lol
  832.             unshift @$content, $self->new_from_lol($_);
  833.         $content->[-1]->{'_parent'} = $self;
  834.         } elsif (ref $_) {  # insert an element
  835.             $_->detach if $_->{'_parent'};
  836.             $_->{'_parent'} = $self;
  837.             unshift(@$content, $_);
  838.         } else {  # insert text segment
  839.             if (@$content && !ref $content->[0]) {
  840.                 # last content element is also text segment -- prepend
  841.                 $content->[0]  = $_ . $content->[0];
  842.             } else {
  843.                 unshift(@$content, $_);
  844.             }
  845.         }
  846.     }
  847.     $self;
  848. }
  849.  
  850. # Cf.  splice ARRAY,OFFSET,LENGTH,LIST
  851.  
  852. =item $h->splice_content($offset, $length, $element_or_text, ...)
  853.  
  854. Detaches the elements from $h's list of content-nodes, starting at
  855. $offset and continuing for $length items, replacing them with the
  856. elements of the following list, if any.  Returns the elements (if any)
  857. removed from the content-list.  If $offset is negative, then it starts
  858. that far from the end of the array, just like Perl's normal C<splice>
  859. function.  If $length and the following list is omitted, removes
  860. everything from $offset onward.
  861.  
  862. The items of content to be added (if any) should each be either a text
  863. segment (a string), an arrayref (which is fed thru C<new_from_lol>),
  864. or an HTML::Element object that's not already
  865. a child of $h.
  866.  
  867. =cut
  868.  
  869. sub splice_content {
  870.     my($self, $offset, $length, @to_add) = @_;
  871.     Carp::croak
  872.       "splice_content requires at least one argument"
  873.       if @_ < 2;  # at least $h->splice_content($offset);
  874.     return $self unless @_;
  875.  
  876.     my $content = ($self->{'_content'} ||= []);
  877.     # prep the list
  878.  
  879.     my @out;
  880.     if(@_ > 2) {  # self, offset, length, ...
  881.       foreach my $n (@to_add) {
  882.         if(ref($n) eq 'ARRAY') {
  883.           $n = $self->new_from_lol($n);
  884.           $n->{'_parent'} = $self;
  885.         } elsif(ref($n)) {
  886.           $n->detach;
  887.           $n->{'_parent'} = $self;
  888.         }
  889.       }
  890.       @out = splice @$content, $offset, $length, @to_add;
  891.     } else {  #  self, offset
  892.       @out = splice @$content, $offset;
  893.     }
  894.     foreach my $n (@out) {
  895.       $n->{'_parent'} = undef if ref $n;
  896.     }
  897.     return @out;
  898. }
  899.  
  900.  
  901. =item $h->detach()
  902.  
  903. This unlinks $h from its parent, by setting its 'parent' attribute to
  904. undef, and by removing it from the content list of its parent (if it
  905. had one).  The return value is the parent that was detached from (or
  906. undef, if $h had no parent to start with).  Note that neither $h nor
  907. its parent are explicitly destroyed.
  908.  
  909. =cut
  910.  
  911. sub detach {
  912.   my $self = $_[0];
  913.   return undef unless(my $parent = $self->{'_parent'});
  914.   $self->{'_parent'} = undef;
  915.   my $cohort = $parent->{'_content'} || return $parent;
  916.   @$cohort = grep { not( ref($_) and $_ eq $self) } @$cohort;
  917.     # filter $self out, if parent has any evident content
  918.   
  919.   return $parent;
  920. }
  921.  
  922.  
  923. =item $h->detach_content()
  924.  
  925. This unlinks $h all of $h's children from $h, and returns them.
  926. Note that these are not explicitly destroyed; for that, you
  927. can just use $h->delete_content.
  928.  
  929. =cut
  930.  
  931. sub detach_content {
  932.   my $c = $_[0]->{'_content'} || return(); # in case of no content
  933.   for (@$c) { $_->{'_parent'} = undef if ref $_; }
  934.   return splice @$c;
  935. }
  936.  
  937.  
  938. =item $h->replace_with( $element_or_text, ... ) 
  939.  
  940. This replaces $h in its parent's content list with the nodes specified.
  941. The element $h (which by then may have no parent) is
  942. returned.  This causes a fatal error if $h has no parent.  
  943. The list of nodes to insert may contain $h, but at most once.
  944. Aside from that possible exception, the nodes to insert should not
  945. already be children of $h's parent.
  946.  
  947. Also, note that this method does not destroy $h -- use
  948. $h->replace_with(...)->delete if you need that.
  949.  
  950. =cut
  951.  
  952. sub replace_with {
  953.   my($self, @replacers) = @_;
  954.   Carp::croak "the target node has no parent"
  955.     unless my($parent) = $self->{'_parent'};
  956.  
  957.   my $parent_content = $parent->{'_content'};
  958.   Carp::croak "the target node's parent has no content!?" 
  959.    unless $parent_content and @$parent_content;
  960.   
  961.   my $replacers_contains_self;
  962.   for(@replacers) {
  963.     if(!ref $_) {
  964.       # noop
  965.     } elsif($_ eq $self) {
  966.       # noop, but check that it's there just once.
  967.       Carp::croak 
  968.         "Replacement list contains several copies of target!"
  969.        if $replacers_contains_self++;
  970.     } elsif($_ eq $parent) {
  971.       Carp::croak "Can't replace an item with its parent!";
  972.     } else {
  973.       $_->detach;
  974.       $_->{'_parent'} = $parent;
  975.       # each of these are necessary
  976.     }
  977.   }
  978.   
  979.   #my $content_r = $self->{'_content'} || [];
  980.   @$parent_content 
  981.    = map { ( ref($_) and $_ eq $self) ? @replacers : $_ }
  982.          @$parent_content
  983.   ;
  984.   
  985.   $self->{'_parent'} = undef unless $replacers_contains_self;
  986.    # if replacers does contain self, then the parent attribute is fine as-is
  987.   
  988.   return $self;
  989. }
  990.  
  991. =item $h->preinsert($element_or_text...)
  992.  
  993. Inserts the given nodes right BEFORE $h in $h's parent's content list.
  994. This causes a fatal error if $h has no parent.  None of the
  995. given nodes should be $h or other children of $h.  Returns $h.
  996.  
  997. =cut
  998.  
  999. sub preinsert {
  1000.   my $self = shift;
  1001.   return $self unless @_;
  1002.   return $self->replace_with(@_, $self);
  1003. }
  1004.  
  1005. =item $h->postinsert($element_or_text...)
  1006.  
  1007. Inserts the given nodes right AFTER $h in $h's parent's content list.
  1008. This causes a fatal error if $h has no parent.  None of the
  1009. given nodes should be $h or other children of $h.  Returns $h.
  1010.  
  1011. =cut
  1012.  
  1013. sub postinsert {
  1014.   my $self = shift;
  1015.   return $self unless @_;
  1016.   return $self->replace_with($self, @_);
  1017. }
  1018.  
  1019.  
  1020. =item $h->replace_with_content()
  1021.  
  1022. This replaces $h in its parent's content list with its own content.
  1023. The element $h (which by then has no parent or content of its own) is
  1024. returned.  This causes a fatal error if $h has no parent.  Also, note
  1025. that this does not destroy $h -- use $h->replace_with_content->delete
  1026. if you need that.
  1027.  
  1028. =cut
  1029.  
  1030. sub replace_with_content {
  1031.   my $self = $_[0];
  1032.   Carp::croak "the target node has no parent"
  1033.     unless my($parent) = $self->{'_parent'};
  1034.  
  1035.   my $parent_content = $parent->{'_content'};
  1036.   Carp::croak "the target node's parent has no content!?" 
  1037.    unless $parent_content and @$parent_content;
  1038.  
  1039.   my $content_r = $self->{'_content'} || [];
  1040.   @$parent_content 
  1041.    = map { ( ref($_) and $_ eq $self) ? @$content_r : $_ }
  1042.          @$parent_content
  1043.   ;
  1044.  
  1045.   $self->{'_parent'} = undef; # detach $self from its parent
  1046.  
  1047.   # Update parentage link, removing from $self's content list
  1048.   for (splice @$content_r) {  $_->{'_parent'} = $parent if ref $_ }
  1049.  
  1050.   return $self;  # note: doesn't destroy it.
  1051. }
  1052.  
  1053.  
  1054.  
  1055. =item $h->delete_content()
  1056.  
  1057. Clears the content of $h, calling $i->delete for each content element.
  1058. Compare with $h->detach_content.
  1059.  
  1060. Returns $h.
  1061.  
  1062. =cut
  1063.  
  1064. sub delete_content
  1065. {
  1066.     for (splice @{ delete($_[0]->{'_content'})
  1067.               # Deleting it here (while holding its value, for the moment)
  1068.               #  will keep calls to detach() from trying to uselessly filter
  1069.               #  the list (as they won't be able to see it once it's been
  1070.               #  deleted)
  1071.             || return($_[0]) # in case of no content
  1072.           },
  1073.           0
  1074.            # the splice is so we can null the array too, just in case
  1075.            # something somewhere holds a ref to it
  1076.         )
  1077.     {
  1078.         $_->delete if ref $_;
  1079.     }
  1080.     $_[0];
  1081. }
  1082.  
  1083.  
  1084.  
  1085. =item $h->delete()
  1086.  
  1087. Detaches this element from its parent (if it has one) and explicitly
  1088. destroys the element and all its descendants.  The return value is
  1089. undef.
  1090.  
  1091. Perl uses garbage collection based on reference counting; when no
  1092. references to a data structure exist, it's implicitly destroyed --
  1093. i.e., when no value anywhere points to a given object anymore, Perl
  1094. knows it can free up the memory that the now-unused object occupies.
  1095.  
  1096. But this fails with HTML::Element trees, because a parent element
  1097. always holds references to its children, and its children elements
  1098. hold references to the parent, so no element ever looks like it's
  1099. I<not> in use.  So, to destroy those elements, you need to call
  1100. $h->delete on the parent.
  1101.  
  1102. =cut
  1103. #'
  1104.  
  1105. sub delete
  1106. {
  1107.     my $self = $_[0];
  1108.     $self->delete_content   # recurse down
  1109.      if $self->{'_content'} && @{$self->{'_content'}};
  1110.     
  1111.     $self->detach if $self->{'_parent'} and $self->{'_parent'}{'_content'};
  1112.      # not the typical case
  1113.  
  1114.     %$self = (); # null out the whole object on the way out
  1115.     return undef;
  1116. }
  1117.  
  1118.  
  1119.  
  1120. =item $h->clone()
  1121.  
  1122. Returns a copy of the element (whose children are clones (recursively)
  1123. of the original's children, if any).
  1124.  
  1125. The returned element is parentless.  Any '_pos' attributes present in the
  1126. source element/tree will be absent in the copy.  For that and other reasons,
  1127. the clone of an HTML::TreeBuilder object that's in mid-parse (i.e, the head
  1128. of a tree that HTML::TreeBuilder is elaborating) cannot (currently) be used
  1129. to continue the parse.
  1130.  
  1131. You are free to clone HTML::TreeBuilder trees, just as long as:
  1132. 1) they're done being parsed, or 2) you don't expect to resume parsing
  1133. into the clone.  (You can continue parsing into the original; it is
  1134. never affected.)
  1135.  
  1136. =cut
  1137.  
  1138. sub clone {
  1139.   #print "Cloning $_[0]\n";
  1140.   my $it = shift;
  1141.   Carp::croak "clone() can be called only as an object method" unless ref $it;
  1142.   Carp::croak "clone() takes no arguments" if @_;
  1143.  
  1144.   my $new = bless { %$it }, ref($it);     # COPY!!! HOOBOY!
  1145.   delete @$new{'_content', '_parent', '_pos', '_head', '_body'};
  1146.   
  1147.   # clone any contents
  1148.   if($it->{'_content'} and @{$it->{'_content'}}) {
  1149.     $new->{'_content'} = [  ref($it)->clone_list( @{$it->{'_content'}} )  ];
  1150.     for(@{$new->{'_content'}}) {
  1151.       $_->{'_parent'} = $new if ref $_;
  1152.     }
  1153.   }
  1154.  
  1155.   return $new;
  1156. }
  1157.  
  1158. =item HTML::Element->clone_list(...nodes...)
  1159.  
  1160. =item or: ref($h)->clone_list(...nodes...)
  1161.  
  1162. Returns a list consisting of a copy of each node given.
  1163. Text segments are simply copied; elements are cloned by
  1164. calling $it->clone on each of them.
  1165.  
  1166. =cut
  1167.  
  1168. sub clone_list {
  1169.   Carp::croak "I can be called only as a class method" if ref shift @_;
  1170.   
  1171.    # all that does is get me here
  1172.   return
  1173.     map
  1174.       {
  1175.         ref($_)
  1176.           ? $_->clone   # copy by method
  1177.           : $_  # copy by evaluation
  1178.       }
  1179.       @_
  1180.   ;
  1181. }
  1182.  
  1183.  
  1184. =item $h->normalize_content
  1185.  
  1186. Normalizes the content of $h -- i.e., concatenates any adjacent text nodes.
  1187. (Any undefined text segments are turned into empty-strings.)
  1188. Note that this does not recurse into $h's descendants.
  1189.  
  1190. =cut
  1191.  
  1192. sub normalize_content {
  1193.   my $start = $_[0];
  1194.   my $c;
  1195.   return unless $c = $start->{'_content'} and ref $c and @$c; # nothing to do
  1196.   # TODO: if we start having text elements, deal with catenating those too?
  1197.   my @stretches = (undef); # start with a barrier
  1198.  
  1199.   # I suppose this could be rewritten to treat stretches as it goes, instead
  1200.   #  of at the end.  But feh.
  1201.  
  1202.   # Scan:
  1203.   for(my $i = 0; $i < @$c; ++$i) {
  1204.     if(defined $c->[$i] and ref $c->[$i]) { # not a text segment
  1205.       if($stretches[0]) {
  1206.         # put in a barrier
  1207.         if($stretches[0][1] == 1) {
  1208.           #print "Nixing stretch at ", $i-1, "\n";
  1209.           undef $stretches[0]; # nix the previous one-node "stretch"
  1210.         } else {
  1211.           #print "End of stretch at ", $i-1, "\n";
  1212.           unshift @stretches, undef
  1213.         }
  1214.       }
  1215.       # else no need for a barrier
  1216.     } else { # text segment
  1217.       $c->[$i] = '' unless defined $c->[$i];
  1218.       if($stretches[0]) {
  1219.         ++$stretches[0][1]; # increase length
  1220.       } else {
  1221.         #print "New stretch at $i\n";
  1222.         unshift @stretches, [$i,1]; # start and length
  1223.       }
  1224.     }
  1225.   }
  1226.  
  1227.   # Now combine.  Note that @stretches is in reverse order, so the indexes
  1228.   # still make sense as we work our way thru (i.e., backwards thru $c).
  1229.   foreach my $s (@stretches) {
  1230.     if($s and $s->[1] > 1) {
  1231.       #print "Stretch at ", $s->[0], " for ", $s->[1], "\n";
  1232.       $c->[$s->[0]] .= join('', splice(@$c, $s->[0] + 1, $s->[1] - 1))
  1233.         # append the subsequent ones onto the first one.
  1234.     }
  1235.   }
  1236.   return;
  1237. }
  1238.  
  1239. =item $h->delete_ignorable_whitespace()
  1240.  
  1241. This traverses under $h and deletes any text segments that are ignorable
  1242. whitespace.  You should not use this if $h under a 'pre' element.
  1243.  
  1244. =cut
  1245.  
  1246. #==========================================================================
  1247.  
  1248. sub delete_ignorable_whitespace {
  1249.   # This doesn't delete all sorts of whitespace that won't actually
  1250.   #  be used in rendering, tho -- that's up to the rendering application.
  1251.   # For example:
  1252.   #   <input type='text' name='foo'>
  1253.   #     [some whitespace]
  1254.   #   <input type='text' name='bar'>
  1255.   # The WS between the two elements /will/ get used by the renderer.
  1256.   # But here:
  1257.   #   <input type='hidden' name='foo' value='1'>
  1258.   #     [some whitespace]
  1259.   #   <input type='text' name='bar' value='2'>
  1260.   # the WS between them won't be rendered in any way, presumably.
  1261.  
  1262.   #my $Debug = 4;
  1263.   die "delete_ignorable_whitespace can be called only as an object method"
  1264.    unless ref $_[0];
  1265.  
  1266.   print "About to tighten up...\n" if $Debug > 2;
  1267.   my(@to_do) = ($_[0]);  # Start off.
  1268.   my($i, $sibs, $ptag, $this); # scratch for the loop...
  1269.   while(@to_do) {
  1270.     if(
  1271.        ( $ptag = ($this = shift @to_do)->{'_tag'} ) eq 'pre'
  1272.        or $ptag eq 'textarea'
  1273.        or $HTML::Tagset::isCDATA_Parent{$ptag}
  1274.     ) {
  1275.       # block the traversal under those
  1276.        print "Blocking traversal under $ptag\n" if $Debug;
  1277.        next;
  1278.     }
  1279.     next unless($sibs = $this->{'_content'} and @$sibs);
  1280.     for($i = $#$sibs; $i >= 0; --$i) { # work backwards thru the list
  1281.       if(ref $sibs->[$i]) {
  1282.         unshift @to_do, $sibs->[$i];
  1283.         # yes, this happens in pre order -- we're going backwards
  1284.         # thru this sibling list.  I doubt it actually matters, tho.
  1285.         next;
  1286.       }
  1287.       next unless $sibs->[$i] =~ m<^\s+$>s; # it's /all/ whitespace
  1288.     
  1289.       print "Under $ptag whose canTighten ",
  1290.           "value is ", 0 + $HTML::Element::canTighten{$ptag}, ".\n"
  1291.        if $Debug > 3;
  1292.  
  1293.       # It's all whitespace...
  1294.       
  1295.       if($i == 0) {
  1296.         if(@$sibs == 1) { # I'm an only child
  1297.           next unless $HTML::Element::canTighten{$ptag}; # parent
  1298.         } else { # I'm leftmost of many
  1299.           # if either my parent or sib are eligible, I'm good.
  1300.           next unless
  1301.            $HTML::Element::canTighten{$ptag} # parent
  1302.            or
  1303.             (ref $sibs->[1]
  1304.              and $HTML::Element::canTighten{$sibs->[1]{'_tag'}} # right sib
  1305.             );
  1306.         }
  1307.       } elsif ($i == $#$sibs) { # I'm rightmost of many
  1308.         # if either my parent or sib are eligible, I'm good.
  1309.         next unless
  1310.            $HTML::Element::canTighten{$ptag} # parent
  1311.            or
  1312.             (ref $sibs->[$i - 1]
  1313.             and $HTML::Element::canTighten{$sibs->[$i - 1]{'_tag'}} # left sib
  1314.             )
  1315.       } else { # I'm the piggy in the middle
  1316.         # My parent doesn't matter -- it all depends on my sibs
  1317.         next
  1318.           unless
  1319.             ref $sibs->[$i - 1] or ref $sibs->[$i + 1];
  1320.          # if NEITHER sib is a node, quit
  1321.          
  1322.         next if
  1323.           # bailout condition: if BOTH are INeligible nodes
  1324.           #  (as opposed to being text, or being eligible nodes)
  1325.             ref $sibs->[$i - 1]
  1326.             and ref $sibs->[$i + 1]
  1327.             and !$HTML::Element::canTighten{$sibs->[$i - 1]{'_tag'}} # left sib
  1328.             and !$HTML::Element::canTighten{$sibs->[$i + 1]{'_tag'}} # right sib
  1329.         ;
  1330.       }
  1331.       # Unknown tags aren't in canTighten and so AREN'T subject to tightening
  1332.  
  1333.       print "  delendum: child $i of $ptag\n" if $Debug > 3;
  1334.       splice @$sibs, $i, 1;
  1335.     }
  1336.      # end of the loop-over-children
  1337.   }
  1338.    # end of the while loop.
  1339.   
  1340.   return;
  1341. }
  1342.  
  1343. #--------------------------------------------------------------------------
  1344.  
  1345. =item $h->insert_element($element, $implicit)
  1346.  
  1347. Inserts (via push_content) a new element under the element at
  1348. $h->pos().  Then updates $h->pos() to point to the inserted element,
  1349. unless $element is a prototypically empty element like "br", "hr",
  1350. "img", etc.  The new $h->pos() is returned.  This method is useful
  1351. only if your particular tree task involves setting $h->pos.
  1352.  
  1353. =cut
  1354.  
  1355. sub insert_element
  1356. {
  1357.     my($self, $tag, $implicit) = @_;
  1358.     return $self->pos() unless $tag; # noop if nothing to insert
  1359.  
  1360.     my $e;
  1361.     if (ref $tag) {
  1362.         $e = $tag;
  1363.         $tag = $e->tag;
  1364.     } else { # just a tag name -- so make the element
  1365.         $e = ($self->{'_element_class'} || __PACKAGE__)->new($tag);
  1366.     ++($self->{'_element_count'}) if exists $self->{'_element_count'};
  1367.      # undocumented.  see TreeBuilder.
  1368.     }
  1369.  
  1370.     $e->{'_implicit'} = 1 if $implicit;
  1371.  
  1372.     my $pos = $self->{'_pos'};
  1373.     $pos = $self unless defined $pos;
  1374.  
  1375.     $pos->push_content($e);
  1376.  
  1377.     $self->{'_pos'} = $pos = $e
  1378.       unless $self->_empty_element_map->{$tag} || $e->{'_empty_element'};
  1379.  
  1380.     $pos;
  1381. }
  1382.  
  1383. #==========================================================================
  1384. # Some things to override in XML::Element
  1385.  
  1386. sub _empty_element_map {
  1387.   \%HTML::Element::emptyElement;
  1388. }
  1389.  
  1390. sub _fold_case_LC {
  1391.   if(wantarray) {
  1392.     shift;
  1393.     map lc($_), @_;
  1394.   } else {
  1395.     return lc($_[1]);
  1396.   }
  1397. }
  1398.  
  1399. sub _fold_case_NOT {
  1400.   if(wantarray) {
  1401.     shift;
  1402.     @_;
  1403.   } else {
  1404.     return $_[1];
  1405.   }
  1406. }
  1407.  
  1408. *_fold_case = \&_fold_case_LC;
  1409.  
  1410. #==========================================================================
  1411.  
  1412. =back
  1413.  
  1414. =head1 DUMPING METHODS
  1415.  
  1416. =over 4
  1417.  
  1418. =item $h->dump()
  1419.  
  1420. =item $h->dump(*FH)  ; # or *FH{IO} or $fh_obj
  1421.  
  1422. Prints the element and all its children to STDOUT (or to a specified
  1423. filehandle), in a format useful
  1424. only for debugging.  The structure of the document is shown by
  1425. indentation (no end tags).
  1426.  
  1427. =cut
  1428.  
  1429. sub dump
  1430. {
  1431.     my($self, $fh, $depth) = @_;
  1432.     $fh = *STDOUT{IO} unless defined $fh;
  1433.     $depth = 0 unless defined $depth;
  1434.     print $fh
  1435.       "  " x $depth,   $self->starttag,   " \@", $self->address,
  1436.       $self->{'_implicit'} ? " (IMPLICIT)\n" : "\n";
  1437.     for (@{$self->{'_content'}}) {
  1438.         if (ref $_) {  # element
  1439.             $_->dump($fh, $depth+1);  # recurse
  1440.         } else {  # text node
  1441.             print $fh "  " x ($depth + 1);
  1442.             if(length($_) > 65 or m<[\x00-\x1F]>) {
  1443.               # it needs prettyin' up somehow or other
  1444.               my $x = (length($_) <= 65) ? $_ : (substr($_,0,65) . '...');
  1445.               $x =~ s<([\x00-\x1F])>
  1446.                      <'\\x'.(unpack("H2",$1))>eg;
  1447.               print $fh qq{"$x"\n};
  1448.             } else {
  1449.               print $fh qq{"$_"\n};
  1450.             }
  1451.         }
  1452.     }
  1453. }
  1454.  
  1455.  
  1456. =item $h->as_HTML() or $h->as_HTML($entities)
  1457.  
  1458. =item or $h->as_HTML($entities, $indent_char)
  1459.  
  1460. =item or $h->as_HTML($entities, $indent_char, \%optional_end_tags)
  1461.  
  1462. Returns a string representing in HTML the element and its
  1463. descendants.  The optional argument C<$entities> specifies a string of
  1464. the entities to encode.  For compatibility with previous versions,
  1465. specify C<'E<lt>E<gt>&'> here.  If omitted or undef, I<all> unsafe
  1466. characters are encoded as HTML entities.  See L<HTML::Entities> for
  1467. details.
  1468.  
  1469. If $indent_char is specified and defined, the HTML to be output is
  1470. intented, using the string you specify (which you probably should
  1471. set to "\t", or some number of spaces, if you specify it).  This
  1472. feature is currently somewhat experimental.  But try it, and feel
  1473. free to email me any bug reports.  (Note that output, although
  1474. indented, is not wrapped.  Patches welcome.)
  1475.  
  1476. If C<\%optional_end_tags> is specified and defined, it should be
  1477. a reference to a hash that holds a true value for every tag name
  1478. whose end tag is optional.  Defaults to
  1479. C<\%HTML::Element::optionalEndTag>, which is an alias to 
  1480. C<%HTML::Tagset::optionalEndTag>, which, at time of writing, contains
  1481. true values for C<p, li, dt, dd>.  A useful value to pass is an empty
  1482. hashref, C<{}>, which means that no end-tags are optional for this dump.
  1483. Otherwise, possibly consider copying C<%HTML::Tagset::optionalEndTag> to a 
  1484. hash of your own, adding or deleting values as you like, and passing
  1485. a reference to that hash.
  1486.  
  1487. =cut
  1488.  
  1489. sub as_HTML {
  1490.   my($self, $entities, $indent, $omissible_map) = @_;
  1491.   #my $indent_on = defined($indent) && length($indent);
  1492.   my @html = ();
  1493.   
  1494.   $omissible_map ||= \%HTML::Element::optionalEndTag;
  1495.   my $empty_element_map = $self->_empty_element_map;
  1496.  
  1497.   my $last_tag_tightenable = 0;
  1498.   my $this_tag_tightenable = 0;
  1499.   my $nonindentable_ancestors = 0;  # count of nonindentible tags over us.
  1500.   
  1501.   my($tag, $node, $start, $depth); # per-iteration scratch
  1502.   
  1503.   if(defined($indent) && length($indent)) {
  1504.     $self->traverse(
  1505.       sub {
  1506.         ($node, $start, $depth) = @_;
  1507.         if(ref $node) { # it's an element
  1508.            
  1509.            $tag = $node->{'_tag'};
  1510.            
  1511.            if($start) { # on the way in
  1512.              if(
  1513.                 ($this_tag_tightenable = $HTML::Element::canTighten{$tag})
  1514.                 and !$nonindentable_ancestors
  1515.                 and $last_tag_tightenable
  1516.              ) {
  1517.                push
  1518.                  @html,
  1519.                  "\n",
  1520.                  $indent x $depth,
  1521.                  $node->starttag($entities),
  1522.                ;
  1523.              } else {
  1524.                push(@html, $node->starttag($entities));
  1525.              }
  1526.              $last_tag_tightenable = $this_tag_tightenable;
  1527.              
  1528.              ++$nonindentable_ancestors
  1529.                if $tag eq 'pre' or $HTML::Tagset::isCDATA_Parent{$tag};             ;
  1530.              
  1531.            } elsif (not($empty_element_map->{$tag} or $omissible_map->{$tag})) {
  1532.              # on the way out
  1533.              if($tag eq 'pre' or $HTML::Tagset::isCDATA_Parent{$tag}) {
  1534.                --$nonindentable_ancestors;
  1535.                $last_tag_tightenable = $HTML::Element::canTighten{$tag};
  1536.                push @html, $node->endtag;
  1537.                
  1538.              } else { # general case
  1539.                if(
  1540.                   ($this_tag_tightenable = $HTML::Element::canTighten{$tag})
  1541.                   and !$nonindentable_ancestors
  1542.                   and $last_tag_tightenable
  1543.                ) {
  1544.                  push
  1545.                    @html,
  1546.                    "\n",
  1547.                    $indent x $depth,
  1548.                    $node->endtag,
  1549.                  ;
  1550.                } else {
  1551.                  push @html, $node->endtag;
  1552.                }
  1553.                $last_tag_tightenable = $this_tag_tightenable;
  1554.                #print "$tag tightenable: $this_tag_tightenable\n";
  1555.              }
  1556.            }
  1557.         } else {  # it's a text segment
  1558.         
  1559.           $last_tag_tightenable = 0;  # I guess this is right
  1560.           HTML::Entities::encode_entities($node, $entities)
  1561.             # That does magic things if $entities is undef.
  1562.            unless $HTML::Tagset::isCDATA_Parent{ $_[3]{'_tag'} };
  1563.             # To keep from amp-escaping children of script et al.
  1564.             # That doesn't deal with descendants; but then, CDATA
  1565.             #  parents shouldn't /have/ descendants other than a
  1566.             #  text children (or comments?)
  1567.           if($nonindentable_ancestors) {
  1568.             push @html, $node; # say no go
  1569.           } else {
  1570.             if($last_tag_tightenable) {
  1571.               $node =~ s<\s+>< >s;
  1572.               #$node =~ s< $><>s;
  1573.               $node =~ s<^ ><>s;
  1574.               push
  1575.                 @html,
  1576.                 "\n",
  1577.                 $indent x $depth,
  1578.                 $node,
  1579.                 #Text::Wrap::wrap($indent x $depth, $indent x $depth, "\n" . $node)
  1580.               ;
  1581.             } else {
  1582.               push
  1583.                 @html,
  1584.                 $node,
  1585.                 #Text::Wrap::wrap('', $indent x $depth, $node)
  1586.               ;
  1587.             }
  1588.           }
  1589.         }
  1590.         1; # keep traversing
  1591.       }
  1592.     );
  1593.     
  1594.   } else { # no indenting -- much simpler code
  1595.     $self->traverse(
  1596.       sub {
  1597.           ($node, $start) = @_;
  1598.           if(ref $node) {
  1599.             $tag = $node->{'_tag'};
  1600.             if($start) { # on the way in
  1601.               push(@html, $node->starttag($entities));
  1602.             } elsif (not($empty_element_map->{$tag} or $omissible_map->{$tag})) {
  1603.               # on the way out
  1604.               push(@html, $node->endtag);
  1605.             }
  1606.           } else {
  1607.             # simple text content
  1608.             HTML::Entities::encode_entities($node, $entities)
  1609.               # That does magic things if $entities is undef.
  1610.              unless $HTML::Tagset::isCDATA_Parent{ $_[3]{'_tag'} };
  1611.               # To keep from amp-escaping children of script et al.
  1612.               # That doesn't deal with descendants; but then, CDATA
  1613.               #  parents shouldn't /have/ descendants other than a
  1614.               #  text children (or comments?)
  1615.             push(@html, $node);
  1616.           }
  1617.          1; # keep traversing
  1618.         }
  1619.     );
  1620.   }
  1621.   
  1622.   join('', @html, "\n");
  1623. }
  1624.  
  1625.  
  1626. =item $h->as_text()
  1627.  
  1628. =item $h->as_text(skip_dels => 1)
  1629.  
  1630. Returns a string consisting of only the text parts of the element's
  1631. descendants.
  1632.  
  1633. Text under 'script' or 'style' elements is never included in what's
  1634. returned.  If C<skip_dels> is true, then text content under "del"
  1635. nodes is not included in what's returned.
  1636.  
  1637. =cut
  1638.  
  1639. sub as_text {
  1640.   # Yet another iteratively implemented traverser
  1641.   my($this,%options) = @_;
  1642.   my $skip_dels = $options{'skip_dels'} || 0;
  1643.   #print "Skip dels: $skip_dels\n";
  1644.   my(@pile) = ($this);
  1645.   my $tag;
  1646.   my $text = '';
  1647.   while(@pile) {
  1648.     if(!defined($pile[0])) { # undef!
  1649.       # no-op
  1650.     } elsif(!ref($pile[0])) { # text bit!  save it!
  1651.       $text .= shift @pile;
  1652.     } else { # it's a ref -- traverse under it
  1653.       unshift @pile, @{$this->{'_content'} || $nillio}
  1654.         unless
  1655.           ($tag = ($this = shift @pile)->{'_tag'}) eq 'style'
  1656.           or $tag eq 'script'
  1657.           or ($skip_dels and $tag eq 'del');
  1658.     }
  1659.   }
  1660.   return $text;
  1661. }
  1662.  
  1663.  
  1664. =item $h->as_XML() or $h->as_XML($entities)
  1665.  
  1666. Returns a string representing in XML the element and its descendants.
  1667. The optional argument C<$entities> specifies a string of the entities
  1668. to encode.  If omitted or undef, I<all> unsafe characters are encoded
  1669. as HTML (!) entities.  See L<HTML::Entities> for details.
  1670.  
  1671. This method is experimental.  If you use this method, tell me what you
  1672. use it for, and if you run into any problems.
  1673.  
  1674. The XML is not indented.
  1675.  
  1676. =cut
  1677.  
  1678. # TODO: make it wrap, if not indent?
  1679.  
  1680. sub as_XML {
  1681.   # based an as_HTML
  1682.   my($self, $entities) = @_;
  1683.   #my $indent_on = defined($indent) && length($indent);
  1684.   my @xml = ();
  1685.   my $empty_element_map = $self->_empty_element_map;
  1686.   
  1687.   my($tag, $node, $start); # per-iteration scratch
  1688.   $self->traverse(
  1689.     sub {
  1690.         ($node, $start) = @_;
  1691.         if(ref $node) { # it's an element
  1692.           $tag = $node->{'_tag'};
  1693.           if($start) { # on the way in
  1694.             if($empty_element_map->{$tag}
  1695.                and !@{$node->{'_content'} || $nillio}
  1696.             ) {
  1697.               push(@xml, $node->starttag_XML($entities,1));
  1698.             } else {
  1699.               push(@xml, $node->starttag_XML($entities));
  1700.             }
  1701.           } else { # on the way out
  1702.             unless($empty_element_map->{$tag}
  1703.                    and !@{$node->{'_content'} || $nillio}
  1704.             ) {
  1705.               push(@xml, $node->endtag_XML());
  1706.             } # otherwise it will have been an <... /> tag.
  1707.           }
  1708.         } else { # it's just text
  1709.           HTML::Entities::encode_entities($node, $entities);
  1710.           push(@xml, $node);
  1711.         }
  1712.        1; # keep traversing
  1713.       }
  1714.   );
  1715.   
  1716.   join('', @xml, "\n");
  1717. }
  1718.  
  1719.  
  1720. =item $h->as_Lisp_form()
  1721.  
  1722. Returns a string representing the element and its descendants as a
  1723. Lisp form.  Unsafe characters are encoded as octal escapes.
  1724.  
  1725. The Lisp form is indented, and contains external ("href", etc.)  as
  1726. well as internal attributes ("_tag", "_content", "_implicit", etc.),
  1727. except for "_parent", which is omitted.
  1728.  
  1729. Current example output for a given element:
  1730.  
  1731.   ("_tag" "img" "border" "0" "src" "pie.png" "usemap" "#main.map")
  1732.  
  1733. This method is experimental.  If you use this method, tell me what you
  1734. use it for, and if you run into any problems.
  1735.  
  1736. =cut
  1737.  
  1738. # NOTES:
  1739. #
  1740. # It's been suggested that attribute names be made :-keywords:
  1741. #   (:_tag "img" :border 0 :src "pie.png" :usemap "#main.map")
  1742. # However, it seems that Scheme has no such data type as :-keywords.
  1743. # So, for the moment at least, I tend toward simplicity, uniformity,
  1744. #  and universality, where everything a string or a list.
  1745.  
  1746. sub as_Lisp_form {
  1747.   my @out;
  1748.   
  1749.   my $sub;
  1750.   my $depth = 0;
  1751.   my(@list, $val);
  1752.   $sub = sub {  # Recursor
  1753.     my $self = $_[0];
  1754.     @list = ('_tag', $self->{'_tag'});
  1755.     @list = () unless defined $list[-1]; # unlikely
  1756.     
  1757.     for (sort keys %$self) { # predictable ordering
  1758.       next if $_ eq '_content' or $_ eq '_tag' or $_ eq '_parent' or $_ eq '/';
  1759.        # Leave the other private attributes, I guess.
  1760.       push @list, $_, $val if defined($val = $self->{$_}); # and !ref $val;
  1761.     }
  1762.     
  1763.     for (@list) {
  1764.       #if(!length $_) {
  1765.       #  $_ = '""';
  1766.       #} elsif(
  1767.       #  $_ eq '0'
  1768.       #  or (
  1769.       #     m/^-?\d+(\.\d+)?$/s
  1770.       #     and $_ ne '-0' # the strange case that that RE lets thru
  1771.       #  ) or (
  1772.       #     m/^-?\.\d+$/s
  1773.       #  )
  1774.       #) {
  1775.       #  # No-op -- don't bother quoting numbers.
  1776.       #  # Note: DOES accept strings like "0123" and ".123" as numbers!
  1777.       #  #  
  1778.       #} else {
  1779.         # octal-escape it
  1780.         s<([^\x20\x21\x23\x27-\x5B\x5D-\x7E])>
  1781.          <sprintf('\\%03o',ord($1))>eg;
  1782.         $_ = qq{"$_"};
  1783.       #}
  1784.     }
  1785.     
  1786.     push @out, ('  ' x $depth) . '(' . join ' ', splice @list;
  1787.     if(@{$self->{'_content'} || $nillio}) {
  1788.       $out[-1] .= " \"_content\" (\n";
  1789.       ++$depth;
  1790.       foreach my $c (@{$self->{'_content'}}) {
  1791.         if(ref($c)) {
  1792.           # an element -- recurse
  1793.           $sub->($c);
  1794.         } else {
  1795.           # a text segment -- stick it in and octal-escape it
  1796.           push @out, $c;
  1797.           $out[-1] =~
  1798.             s<([^\x20\x21\x23\x27-\x5B\x5D-\x7E])>
  1799.              <sprintf('\\%03o',ord($1))>eg;
  1800.           # And quote and indent it.
  1801.           $out[-1] .= "\"\n";
  1802.           $out[-1] = ('  ' x $depth) . '"' . $out[-1];
  1803.         }
  1804.       }
  1805.       --$depth;
  1806.       substr($out[-1],-1) = "))\n"; # end of _content and of the element
  1807.     } else {
  1808.       $out[-1] .= ")\n";
  1809.     }
  1810.     return;
  1811.   };
  1812.   
  1813.   $sub->($_[0]);
  1814.   undef $sub;
  1815.   return join '', @out;
  1816. }
  1817.  
  1818.  
  1819. sub format
  1820. {
  1821.     my($self, $formatter) = @_;
  1822.     unless (defined $formatter) {
  1823.         require HTML::FormatText;
  1824.         $formatter = HTML::FormatText->new();
  1825.     }
  1826.     $formatter->format($self);
  1827. }
  1828.  
  1829.  
  1830.  
  1831. =item $h->starttag() or $h->starttag($entities)
  1832.  
  1833. Returns a string representing the complete start tag for the element.
  1834. I.e., leading "<", tag name, attributes, and trailing ">".  Attributes
  1835. values that don't consist entirely of digits are surrounded with
  1836. double-quotes, and appropriate characters are encoded.  If C<$entities>
  1837. is omitted or undef, I<all> unsafe characters are encoded as HTML
  1838. entities.  See L<HTML::Entities> for details.  If you specify some
  1839. value for C<$entities>, remember to include the double-quote character in
  1840. it.  (Previous versions of this module would basically behave as if
  1841. C<'&"E<gt>'> were specified for C<$entities>.)
  1842.  
  1843. =cut
  1844.  
  1845. sub starttag
  1846. {
  1847.     my($self, $entities) = @_;
  1848.     
  1849.     my $name = $self->{'_tag'};
  1850.     
  1851.     return        $self->{'text'}        if $name eq '~literal';
  1852.     
  1853.     return "<!" . $self->{'text'} . ">"  if $name eq '~declaration';
  1854.     
  1855.     return "<?" . $self->{'text'} . ">"  if $name eq '~pi';
  1856.     
  1857.     if($name eq '~comment') {
  1858.       if(ref($self->{'text'} || '') eq 'ARRAY') {
  1859.         # Does this ever get used?  And is this right?
  1860.         return 
  1861.           "<!" .
  1862.           join(' ', map("--$_--", @{$self->{'text'}}))
  1863.           .  ">"
  1864.        ;
  1865.       } else {
  1866.         return "<!--" . $self->{'text'} . "-->"
  1867.       }
  1868.     }
  1869.     
  1870.     my $tag = $html_uc ? "<\U$name" : "<\L$name";
  1871.     my $val;
  1872.     for (sort keys %$self) { # predictable ordering
  1873.         next if !length $_ or m/^_/s or $_ eq '/';
  1874.         $val = $self->{$_};
  1875.         next if !defined $val; # or ref $val;
  1876.         if ($_ eq $val &&   # if attribute is boolean, for this element
  1877.             exists($HTML::Element::boolean_attr{$name}) &&
  1878.             (ref($HTML::Element::boolean_attr{$name})
  1879.               ? $HTML::Element::boolean_attr{$name}{$_}
  1880.               : $HTML::Element::boolean_attr{$name} eq $_)
  1881.         ) {
  1882.             $tag .= $html_uc ? " \U$_" : " \L$_";
  1883.         } else { # non-boolean attribute
  1884.             if ($val !~ m/^[0-9]+$/s) { # quote anything not purely numeric
  1885.               # Might as well double-quote everything, for simplicity's sake
  1886.               HTML::Entities::encode_entities($val, $entities);
  1887.               $val = qq{"$val"};
  1888.             }
  1889.             $tag .= $html_uc ? qq{ \U$_\E=$val} : qq{ \L$_\E=$val};
  1890.         }
  1891.     }
  1892.     "$tag>";
  1893. }
  1894.  
  1895.  
  1896. # TODO: document?
  1897. sub starttag_XML
  1898. {
  1899.     my($self, $entities) = @_;
  1900.      # and a third parameter to signal emptiness
  1901.     
  1902.     my $name = $self->{'_tag'};
  1903.     
  1904.     return        $self->{'text'}        if $name eq '~literal';
  1905.     
  1906.     return '<!' . $self->{'text'}. '>'   if $name eq '~declaration';
  1907.     
  1908.     return "<?" . $self->{'text'} . "?>" if $name eq '~pi';
  1909.     
  1910.     if($name eq '~comment') {
  1911.       
  1912.       if(ref($self->{'text'} || '') eq 'ARRAY') {
  1913.         # Does this ever get used?  And is this right?
  1914.         $name = join(' ', @{$self->{'text'}});
  1915.       } else {
  1916.         $name = $self->{'text'};
  1917.       }
  1918.       $name =~ s/--/--/g; # can't have double --'s in XML comments
  1919.       return "<!-- $name -->";
  1920.     }
  1921.     
  1922.     my $tag = "<$name";
  1923.     my $val;
  1924.     for (sort keys %$self) { # predictable ordering
  1925.         next if !length $_ or  m/^_/s or $_ eq '/';
  1926.         # Hm -- what to do if val is undef?
  1927.         # I suppose that shouldn't ever happen.
  1928.         next if !defined($val = $self->{$_}); # or ref $val;
  1929.         HTML::Entities::encode_entities($val, $entities);
  1930.         $tag .= qq{ $_="$val"};
  1931.     }
  1932.     @_ == 3 ? "$tag />" : "$tag>";
  1933. }
  1934.  
  1935.  
  1936.  
  1937. =item $h->endtag()
  1938.  
  1939. Returns a string representing the complete end tag for this element.
  1940. I.e., "</", tag name, and ">".
  1941.  
  1942. =cut
  1943.  
  1944. sub endtag
  1945. {
  1946.     $html_uc ? "</\U$_[0]->{'_tag'}>" : "</\L$_[0]->{'_tag'}>";
  1947. }
  1948.  
  1949. # TODO: document?
  1950. sub endtag_XML
  1951. {
  1952.     "</$_[0]->{'_tag'}>";
  1953. }
  1954.  
  1955.  
  1956. #==========================================================================
  1957. # This, ladies and germs, is an iterative implementation of a
  1958. # recursive algorithm.  DON'T TRY THIS AT HOME.
  1959. # Basically, the algorithm says:
  1960. #
  1961. # To traverse:
  1962. #   1: pre-order visit this node
  1963. #   2: traverse any children of this node
  1964. #   3: post-order visit this node, unless it's a text segment,
  1965. #       or a prototypically empty node (like "br", etc.)
  1966. # Add to that the consideration of the callbacks' return values,
  1967. # so you can block visitation of the children, or siblings, or
  1968. # abort the whole excursion, etc.
  1969. #
  1970. # So, why all this hassle with making the code iterative?
  1971. # It makes for real speed, because it eliminates the whole
  1972. # hassle of Perl having to allocate scratch space for each
  1973. # instance of the recursive sub.  Since the algorithm
  1974. # is basically simple (and not all recursive ones are!) and
  1975. # has few necessary lexicals (basically just the current node's
  1976. # content list, and the current position in it), it was relatively
  1977. # straightforward to store that information not as the frame
  1978. # of a sub, but as a stack, i.e., a simple Perl array (well, two
  1979. # of them, actually: one for content-listrefs, one for indexes of
  1980. # current position in each of those).
  1981.  
  1982. my $NIL = [];
  1983. sub traverse {
  1984.   my($start, $callback, $ignore_text) = @_;
  1985.  
  1986.   Carp::croak "traverse can be called only as an object method"
  1987.    unless ref $start;
  1988.   
  1989.   Carp::croak('must provide a callback for traverse()!')
  1990.    unless defined $callback and ref $callback;
  1991.   
  1992.   # Elementary type-checking:
  1993.   my($c_pre, $c_post);
  1994.   if(UNIVERSAL::isa($callback, 'CODE')) {
  1995.     $c_pre = $c_post = $callback;
  1996.   } elsif(UNIVERSAL::isa($callback,'ARRAY')) {
  1997.     ($c_pre, $c_post) = @$callback;
  1998.     Carp::croak("pre-order callback \"$c_pre\" is true but not a coderef!")
  1999.      if $c_pre and not UNIVERSAL::isa($c_pre, 'CODE');
  2000.     Carp::croak("pre-order callback \"$c_post\" is true but not a coderef!")
  2001.      if $c_post and not UNIVERSAL::isa($c_post, 'CODE');
  2002.     return $start unless $c_pre or $c_post;
  2003.      # otherwise there'd be nothing to actually do!
  2004.   } else {
  2005.     Carp::croak("$callback is not a known kind of reference")
  2006.      unless ref($callback);
  2007.   }
  2008.   
  2009.   my $empty_element_map = $start->_empty_element_map;
  2010.   
  2011.   my(@C) = [$start]; # a stack containing lists of children
  2012.   my(@I) = (-1); # initial value must be -1 for each list
  2013.     # a stack of indexes to current position in corresponding lists in @C
  2014.   # In each of these, 0 is the active point
  2015.   
  2016.   # scratch:
  2017.   my(
  2018.     $rv,   # return value of callback
  2019.     $this, # current node
  2020.     $content_r, # child list of $this
  2021.   );
  2022.   
  2023.   
  2024.   # THE BIG LOOP
  2025.   while(@C) {
  2026.     # Move to next item in this frame
  2027.     #print "Loop: \@C has ", scalar(@C), " frames: @C\n";
  2028.     if(!defined($I[0]) or ++$I[0] >= @{$C[0]}) {
  2029.       # We either went off the end of this list, or aborted the list
  2030.       # So call the post-order callback:
  2031.       if($c_post
  2032.          and defined $I[0]
  2033.          and @C > 1
  2034.           # to keep the next line from autovivifying
  2035.          and defined($this = $C[1][ $I[1] ]) # sanity, and
  2036.           # suppress callbacks on exiting the fictional top frame
  2037.          and ref($this) # sanity
  2038.          and not(
  2039.                  $this->{'_empty_element'}
  2040.                  || $empty_element_map->{$this->{'_tag'} || ''}
  2041.                 ) # things that don't get post-order callbacks
  2042.       ) {
  2043.         shift @I;
  2044.         shift @C;
  2045.         #print "Post! at depth", scalar(@I), "\n";
  2046.         $rv = $c_post->(
  2047.            #map $_, # copy to avoid any messiness
  2048.            $this,           # 0: this
  2049.            0,               # 1: startflag (0 for post-order call)
  2050.            @I - 1,          # 2: depth
  2051.         );
  2052.         
  2053.         if(defined($rv) and ref($rv) eq $travsignal_package) {
  2054.           $rv = $$rv; #deref
  2055.           if($rv eq 'ABORT') {
  2056.             last; # end of this excursion!
  2057.           } elsif($rv eq 'PRUNE') {
  2058.             # NOOP on post!!
  2059.           } elsif($rv eq 'PRUNE_SOFTLY') {
  2060.             # NOOP on post!!
  2061.           } elsif($rv eq 'OK') {
  2062.             # noop
  2063.           } elsif($rv eq 'PRUNE_UP') {
  2064.             $I[0] = undef;
  2065.           } else {
  2066.             die "Unknown travsignal $rv\n";
  2067.             # should never happen
  2068.           }
  2069.         }
  2070.         
  2071.       } else {
  2072.         #print "Oomph.  Callback suppressed\n";
  2073.         shift @I;
  2074.         shift @C;
  2075.       }
  2076.       next;
  2077.     }
  2078.     
  2079.     $this = $C[0][ $I[0] ];
  2080.     
  2081.     if($c_pre) {
  2082.       if(defined $this and ref $this) { # element
  2083.         $rv = $c_pre->(
  2084.            #map $_, # copy to avoid any messiness
  2085.            $this,           # 0: this
  2086.            1,               # 1: startflag (1 for pre-order call)
  2087.            @I - 1,          # 2: depth
  2088.         );
  2089.       } else { # text segment
  2090.         next if $ignore_text;
  2091.         $rv = $c_pre->(
  2092.            #map $_, # copy to avoid any messiness
  2093.            $this,           # 0: this
  2094.            1,               # 1: startflag (1 for pre-order call)
  2095.            @I - 1,          # 2: depth
  2096.            $C[1][ $I[1] ],  # 3: parent
  2097.                # And there will always be a $C[1], since
  2098.                #  we can't start traversing at a text node
  2099.            $I[0]            # 4: index of self in parent's content list
  2100.         );
  2101.       }
  2102.       if(not $rv) { # returned false.  Same as PRUNE.
  2103.         next; # prune
  2104.       } elsif(ref($rv) eq $travsignal_package) {
  2105.         $rv = $$rv; # deref
  2106.         if($rv eq 'ABORT') {
  2107.           last; # end of this excursion!
  2108.         } elsif($rv eq 'PRUNE') {
  2109.           next;
  2110.         } elsif($rv eq 'PRUNE_SOFTLY') {
  2111.           if(ref($this)
  2112.              and
  2113.              not($this->{'_empty_element'}
  2114.                  || $empty_element_map->{$this->{'_tag'} || ''})
  2115.           ) {
  2116.             # push a dummy empty content list just to trigger a post callback
  2117.             unshift @I, -1;
  2118.             unshift @C, $NIL;
  2119.           }
  2120.           next;
  2121.         } elsif($rv eq 'OK') {
  2122.           # noop
  2123.         } elsif($rv eq 'PRUNE_UP') {
  2124.           $I[0] = undef;
  2125.           next;
  2126.           
  2127.           # equivalent of last'ing out of the current child list.
  2128.           
  2129.         # Used to have PRUNE_UP_SOFTLY and ABORT_SOFTLY here, but the code
  2130.         # for these was seriously upsetting, served no particularly clear
  2131.         # purpose, and could not, I think, be easily implemented with a
  2132.         # recursive routine.  All bad things!
  2133.         } else {
  2134.           die "Unknown travsignal $rv\n";
  2135.           # should never happen
  2136.         }
  2137.       }
  2138.       # else fall thru to meaning same as \'OK'.
  2139.     }
  2140.     # end of pre-order calling
  2141.     
  2142.     # Now queue up content list for the current element...
  2143.     if(ref $this
  2144.        and
  2145.        not( # ...except for those which...
  2146.          not($content_r = $this->{'_content'} and @$content_r)
  2147.             # ...have empty content lists...
  2148.          and $this->{'_empty_element'} || $empty_element_map->{$this->{'_tag'} || ''}
  2149.             # ...and that don't get post-order callbacks
  2150.        )
  2151.     ) {
  2152.       unshift @I, -1;
  2153.       unshift @C, $content_r || $NIL;
  2154.       #print $this->{'_tag'}, " ($this) adds content_r ", $C[0], "\n";
  2155.     }
  2156.   }
  2157.   return $start;
  2158. }
  2159.  
  2160.  
  2161. =back
  2162.  
  2163. =head1 SECONDARY STRUCTURAL METHODS
  2164.  
  2165. These methods all involve some structural aspect of the tree;
  2166. either they report some aspect of the tree's structure, or they involve
  2167. traversal down the tree, or walking up the tree.
  2168.  
  2169. =over 4
  2170.  
  2171. =item $h->is_inside('tag', ...) or $h->is_inside($element, ...)
  2172.  
  2173. Returns true if the $h element is, or is contained anywhere inside an
  2174. element that is any of the ones listed, or whose tag name is any of
  2175. the tag names listed.
  2176.  
  2177. =cut
  2178.  
  2179. sub is_inside {
  2180.   my $self = shift;
  2181.   return undef unless @_; # if no items specified, I guess this is right.
  2182.  
  2183.   my $current = $self;
  2184.       # the loop starts by looking at the given element
  2185.   while (defined $current and ref $current) {
  2186.     for (@_) {
  2187.       if(ref) { # element
  2188.         return 1 if $_ eq $current;
  2189.       } else { # tag name
  2190.         return 1 if $_ eq $current->{'_tag'};
  2191.       }
  2192.     }
  2193.     $current = $current->{'_parent'};
  2194.   }
  2195.   0;
  2196. }
  2197.  
  2198. =item $h->is_empty()
  2199.  
  2200. Returns true if $h has no content, i.e., has no elements or text
  2201. segments under it.  In other words, this returns true if $h is a leaf
  2202. node, AKA a terminal node.  Do not confuse this sense of "empty" with
  2203. another sense that it can have in SGML/HTML/XML terminology, which
  2204. means that the element in question is of the type (like HTML's "hr",
  2205. "br", "img", etc.) that I<can't> have any content.
  2206.  
  2207. That is, a particular "p" element may happen to have no content, so
  2208. $that_p_element->is_empty will be true -- even though the prototypical
  2209. "p" element isn't "empty" (not in the way that the prototypical "hr"
  2210. element is).
  2211.  
  2212. If you think this might make for potentially confusing code, consider
  2213. simply using the clearer exact equivalent:  not($h->content_list)
  2214.  
  2215. =cut
  2216.  
  2217. sub is_empty
  2218. {
  2219.   my $self = shift;
  2220.   !$self->{'_content'} || !@{$self->{'_content'}};
  2221. }
  2222.  
  2223.  
  2224. =item $h->pindex()
  2225.  
  2226. Return the index of the element in its parent's contents array, such
  2227. that $h would equal
  2228.  
  2229.   $h->parent->content->[$h->pindex]
  2230.   or
  2231.   ($h->parent->content_list)[$h->pindex]
  2232.  
  2233. assuming $h isn't root.  If the element $h is root, then
  2234. $h->pindex returns undef.
  2235.  
  2236. =cut
  2237.  
  2238. #'
  2239. sub pindex {
  2240.   my $self = shift;
  2241.  
  2242.   my $parent = $self->{'_parent'} || return undef;
  2243.   my $pc =  $parent->{'_content'} || return undef;
  2244.   for(my $i = 0; $i < @$pc; ++$i) {
  2245.     return $i  if  ref $pc->[$i] and $pc->[$i] eq $self;
  2246.   }
  2247.   return undef; # we shouldn't ever get here
  2248. }
  2249.  
  2250. #--------------------------------------------------------------------------
  2251.  
  2252. =item $h->left()
  2253.  
  2254. In scalar context: returns the node that's the immediate left sibling
  2255. of $h.  If $h is the leftmost (or only) child of its parent (or has no
  2256. parent), then this returns undef.
  2257.  
  2258. In list context: returns all the nodes that're the left siblings of $h
  2259. (starting with the leftmost).  If $h is the leftmost (or only) child
  2260. of its parent (or has no parent), then this returns empty-list.
  2261.  
  2262. (See also $h->preinsert(LIST).)
  2263.  
  2264. =cut
  2265.  
  2266. sub left {
  2267.   Carp::croak "left() is supposed to be an object method"
  2268.    unless ref $_[0];
  2269.   my $pc =
  2270.     (
  2271.      $_[0]->{'_parent'} || return
  2272.     )->{'_content'} || die "parent is childless?";
  2273.  
  2274.   die "parent is childless" unless @$pc;
  2275.   return if @$pc == 1; # I'm an only child
  2276.  
  2277.   if(wantarray) {
  2278.     my @out;
  2279.     foreach my $j (@$pc) {
  2280.       return @out if ref $j and $j eq $_[0];
  2281.       push @out, $j;
  2282.     }
  2283.   } else {
  2284.     for(my $i = 0; $i < @$pc; ++$i) {
  2285.       return $i ? $pc->[$i - 1] : undef
  2286.        if ref $pc->[$i] and $pc->[$i] eq $_[0];
  2287.     }
  2288.   }
  2289.  
  2290.   die "I'm not in my parent's content list?";
  2291.   return;
  2292. }
  2293.  
  2294. =item $h->right()
  2295.  
  2296. In scalar context: returns the node that's the immediate right sibling
  2297. of $h.  If $h is the rightmost (or only) child of its parent (or has
  2298. no parent), then this returns undef.
  2299.  
  2300. In list context: returns all the nodes that're the right siblings of
  2301. $h, strting with the leftmost.  If $h is the rightmost (or only) child
  2302. of its parent (or has no parent), then this returns empty-list.
  2303.  
  2304. (See also $h->postinsert(LIST).)
  2305.  
  2306. =cut
  2307.  
  2308. sub right {
  2309.   Carp::croak "right() is supposed to be an object method"
  2310.    unless ref $_[0];
  2311.   my $pc =
  2312.     (
  2313.      $_[0]->{'_parent'} || return
  2314.     )->{'_content'} || die "parent is childless?";
  2315.  
  2316.   die "parent is childless" unless @$pc;
  2317.   return if @$pc == 1; # I'm an only child
  2318.  
  2319.   if(wantarray) {
  2320.     my(@out, $seen);
  2321.     foreach my $j (@$pc) {
  2322.       if($seen) {
  2323.         push @out, $j;
  2324.       } else {
  2325.         $seen = 1 if ref $j and $j eq $_[0];
  2326.       }
  2327.     }
  2328.     die "I'm not in my parent's content list?" unless $seen;
  2329.     return @out;
  2330.   } else {
  2331.     for(my $i = 0; $i < @$pc; ++$i) {
  2332.       return +($i == $#$pc) ? undef : $pc->[$i+1]
  2333.        if ref $pc->[$i] and $pc->[$i] eq $_[0];
  2334.     }
  2335.     die "I'm not in my parent's content list?";
  2336.     return;
  2337.   }
  2338. }
  2339.  
  2340. #--------------------------------------------------------------------------
  2341.  
  2342. =item $h->address()
  2343.  
  2344. Returns a string representing the location of this node in the tree.
  2345. The address consists of numbers joined by a '.', starting with '0',
  2346. and followed by the pindexes of the nodes in the tree that are
  2347. ancestors of $h, starting from the top.
  2348.  
  2349. So if the way to get to a node starting at the root is to go to child
  2350. 2 of the root, then child 10 of that, and then child 0 of that, and
  2351. then you're there -- then that node's address is "0.2.10.0".
  2352.  
  2353. As a bit of a special case, the address of the root is simply "0".
  2354.  
  2355. I forsee this being used mainly for debugging, but you may
  2356. find your own uses for it.
  2357.  
  2358. =item $h->address($address)
  2359.  
  2360. This returns the node (whether element or text-segment) at
  2361. the given address in the tree that $h is a part of.  (That is,
  2362. the address is resolved starting from $h->root.)
  2363.  
  2364. If there is no node at the given address, this returns undef.
  2365.  
  2366. You can specify "relative addressing" (i.e., that indexing is supposed
  2367. to start from $h and not from $h->root) by having the address start
  2368. with a period -- e.g., $h->address(".3.2") will look at child 3 of $h,
  2369. and child 2 of that.
  2370.  
  2371. =cut
  2372.  
  2373. sub address {
  2374.   if(@_ == 1) { # report-address form
  2375.     return
  2376.       join('.',
  2377.         reverse( # so it starts at the top
  2378.           map($_->pindex() || '0', # so that root's undef -> '0'
  2379.             $_[0], # self and...
  2380.             $_[0]->lineage
  2381.           )
  2382.         )
  2383.       )
  2384.     ;
  2385.   } else { # get-node-at-address
  2386.     my @stack = split(/\./, $_[1]);
  2387.     my $here;
  2388.  
  2389.     if(@stack and !length $stack[0]) { # relative addressing
  2390.       $here = $_[0];
  2391.       shift @stack;
  2392.     } else { # absolute addressing
  2393.       return undef unless 0 == shift @stack; # to pop the initial 0-for-root
  2394.       $here = $_[0]->root;
  2395.     }
  2396.  
  2397.     while(@stack) {
  2398.       return undef
  2399.        unless
  2400.          $here->{'_content'}
  2401.          and @{$here->{'_content'}} > $stack[0];
  2402.             # make sure the index isn't too high
  2403.       $here = $here->{'_content'}[ shift @stack ];
  2404.       return undef if @stack and not ref $here;
  2405.         # we hit a text node when we expected a non-terminal element node
  2406.     }
  2407.     
  2408.     return $here;
  2409.   }
  2410. }
  2411.  
  2412.  
  2413. =item $h->depth()
  2414.  
  2415. Returns a number expressing $h's depth within its tree, i.e., how many
  2416. steps away it is from the root.  If $h has no parent (i.e., is root),
  2417. its depth is 0.
  2418.  
  2419. =cut
  2420.  
  2421. #'
  2422. sub depth {
  2423.   my $here = $_[0];
  2424.   my $depth = 0;
  2425.   while(defined($here = $here->{'_parent'}) and ref($here)) {
  2426.     ++$depth;
  2427.   }
  2428.   return $depth;
  2429. }
  2430.  
  2431.  
  2432.  
  2433. =item $h->root()
  2434.  
  2435. Returns the element that's the top of $h's tree.  If $h is root, this
  2436. just returns $h.  (If you want to test whether $h I<is> the root,
  2437. instead of asking what its root is, just test not($h->parent).)
  2438.  
  2439. =cut
  2440.  
  2441. #'
  2442. sub root {
  2443.   my $here = my $root = shift;
  2444.   while(defined($here = $here->{'_parent'}) and ref($here)) {
  2445.     $root = $here;
  2446.   }
  2447.   return $root;
  2448. }
  2449.  
  2450.  
  2451. =item $h->lineage()
  2452.  
  2453. Returns the list of $h's ancestors, starting with its parent, and then
  2454. that parent's parent, and so on, up to the root.  If $h is root, this
  2455. returns an empty list.
  2456.  
  2457. If you simply want a count of the number of elements in $h's lineage,
  2458. use $h->depth.
  2459.  
  2460. =cut
  2461.  
  2462. #'
  2463. sub lineage {
  2464.   my $here = shift;
  2465.   my @lineage;
  2466.   while(defined($here = $here->{'_parent'}) and ref($here)) {
  2467.     push @lineage, $here;
  2468.   }
  2469.   return @lineage;
  2470. }
  2471.  
  2472.  
  2473. =item $h->lineage_tag_names()
  2474.  
  2475. Returns the list of the tag names of $h's ancestors, starting
  2476. with its parent, and that parent's parent, and so on, up to the
  2477. root.  If $h is root, this returns an empty list.
  2478. Example output: C<('em', 'td', 'tr', 'table', 'body', 'html')>
  2479.  
  2480. =cut
  2481.  
  2482. #'
  2483. sub lineage_tag_names {
  2484.   my $here = my $start = shift;
  2485.   my @lineage_names;
  2486.   while(defined($here = $here->{'_parent'}) and ref($here)) {
  2487.     push @lineage_names, $here->{'_tag'};
  2488.   }
  2489.   return @lineage_names;
  2490. }
  2491.  
  2492.  
  2493. =item $h->descendants()
  2494.  
  2495. In list context, returns the list of all $h's descendant elements,
  2496. listed in pre-order (i.e., an element appears before its
  2497. content-elements).  Text segments DO NOT appear in the list.
  2498. In scalar context, returns a count of all such elements.
  2499.  
  2500. =cut
  2501.  
  2502. #'
  2503. sub descendants {
  2504.   my $start = shift;
  2505.   if(wantarray) {
  2506.     my @descendants;
  2507.     $start->traverse(
  2508.       [ # pre-order sub only
  2509.         sub {
  2510.           push(@descendants, $_[0]);
  2511.           return 1;
  2512.         },
  2513.         undef # no post
  2514.       ],
  2515.       1, # ignore text
  2516.     );
  2517.     shift @descendants; # so $self doesn't appear in the list
  2518.     return @descendants;
  2519.   } else { # just returns a scalar
  2520.     my $descendants = -1; # to offset $self being counted
  2521.     $start->traverse(
  2522.       [ # pre-order sub only
  2523.         sub {
  2524.           ++$descendants;
  2525.           return 1;
  2526.         },
  2527.         undef # no post
  2528.       ],
  2529.       1, # ignore text
  2530.     );
  2531.     return $descendants;
  2532.   }
  2533. }
  2534.  
  2535.  
  2536. =item $h->find_by_tag_name('tag', ...)
  2537.  
  2538. In list context, returns a list of elements at or under $h that have
  2539. any of the specified tag names.  In scalar context, returns the first
  2540. (in pre-order traversal of the tree) such element found, or undef if
  2541. none.
  2542.  
  2543. =cut
  2544.  
  2545. sub find_by_tag_name {
  2546.   my(@pile) = shift(@_); # start out the to-do stack for the traverser
  2547.   Carp::croak "find_by_tag_name can be called only as an object method"
  2548.    unless ref $pile[0];
  2549.   return() unless @_;
  2550.   my(@tags) = $pile[0]->_fold_case(@_);
  2551.   my(@matching, $this, $this_tag);
  2552.   while(@pile) {
  2553.     $this_tag = ($this = shift @pile)->{'_tag'};
  2554.     foreach my $t (@tags) {
  2555.       if($t eq $this_tag) {
  2556.         if(wantarray) {
  2557.           push @matching, $this;
  2558.           last;
  2559.         } else {
  2560.           return $this;
  2561.         }
  2562.       }
  2563.     }
  2564.     unshift @pile, grep ref($_), @{$this->{'_content'} || next};
  2565.   }
  2566.   return @matching if wantarray;
  2567.   return;
  2568. }
  2569.  
  2570. =item $h->find_by_attribute('attribute', 'value')
  2571.  
  2572. In a list context, returns a list of elements at or under $h that have
  2573. the specified attribute, and have the given value for that attribute.
  2574. In a scalar context, returns the first (in pre-order traversal of the
  2575. tree) such element found, or undef if none.
  2576.  
  2577. This method is B<deprecated> in favor of the more expressive
  2578. C<look_down> method, which new code should use instead.
  2579.  
  2580. =cut
  2581.  
  2582.  
  2583. sub find_by_attribute {
  2584.   # We could limit this to non-internal attributes, but hey.
  2585.   my($self, $attribute, $value) = @_;
  2586.   Carp::croak "Attribute must be a defined value!" unless defined $attribute;
  2587.   $attribute =  $self->_fold_case($attribute);
  2588.   
  2589.   my @matching;
  2590.   my $wantarray = wantarray;
  2591.   my $quit;
  2592.   $self->traverse(
  2593.     [ # pre-order only
  2594.       sub {
  2595.         if( exists $_[0]{$attribute}
  2596.              and $_[0]{$attribute} eq $value
  2597.         ) {
  2598.           push @matching, $_[0];
  2599.           return HTML::Element::ABORT unless $wantarray; # only take the first
  2600.         }
  2601.         1; # keep traversing
  2602.       },
  2603.       undef # no post
  2604.     ],
  2605.     1, # yes, ignore text nodes.
  2606.   );
  2607.  
  2608.   if($wantarray) {
  2609.     return @matching;
  2610.   } else {
  2611.     return undef unless @matching;
  2612.     return $matching[0];
  2613.   }
  2614. }
  2615.  
  2616. #--------------------------------------------------------------------------
  2617.  
  2618. =item $h->look_down( ...criteria... )
  2619.  
  2620. This starts at $h and looks thru its element descendants (in
  2621. pre-order), looking for elements matching the criteria you specify.
  2622. In list context, returns all elements that match all the given
  2623. criteria; in scalar context, returns the first such element (or undef,
  2624. if nothing matched).
  2625.  
  2626. There are two kinds of criteria you can specify:
  2627.  
  2628. =over
  2629.  
  2630. =item (attr_name, attr_value)
  2631.  
  2632. This means you're looking for an element with that value for that
  2633. attribute.  Example: C<"alt", "pix!">.  Consider that you can search
  2634. on internal attribute values too: C<"_tag", "p">.
  2635.  
  2636. =item a coderef
  2637.  
  2638. This means you're looking for elements where coderef->(each_element)
  2639. returns true.  Example:
  2640.  
  2641.   my @wide_pix_images
  2642.     = $h->look_down(
  2643.                     "_tag", "img",
  2644.                     "alt", "pix!",
  2645.                     sub { $_[0]->attr('width') > 350 }
  2646.                    );
  2647.  
  2648. =back
  2649.  
  2650. Note that C<(attr_name, attr_value)> criteria are faster than coderef
  2651. criteria, so should presumably be put before them in your list of
  2652. criteria.  That is, in the example above, the sub ref is called only
  2653. for elements that have already passed the criteria of having a "_tag"
  2654. attribute with value "img", and an "alt" attribute with value "pix!".
  2655. If the coderef were first, it would be called on every element, and
  2656. I<then> what elements pass that criterion (i.e., elements for which
  2657. the coderef returned true) would be checked for their "_tag" and "alt"
  2658. attributes.
  2659.  
  2660. Note that comparison of string attribute-values against the string
  2661. value in C<(attr_name, attr_value)> is case-INsensitive!  A criterion
  2662. of C<('align', 'right')> I<will> match an element whose "align" value
  2663. is "RIGHT", or "right" or "rIGhT", etc.
  2664.  
  2665. Note also that C<look_down> considers "" (empty-string) and undef to
  2666. be different things, in attribute values.  So this:
  2667.  
  2668.   $h->look_down("alt", "")
  2669.  
  2670. will find elements I<with> an "alt" attribute, but where the value for
  2671. the "alt" attribute is "".  But this:
  2672.  
  2673.   $h->look_down("alt", undef)
  2674.  
  2675. is the same as:
  2676.  
  2677.   $h->look_down(sub { !defined($_[0]->attr('alt')) } )
  2678.  
  2679. That is, it finds elements that do not have an "alt" attribute at all
  2680. (or that do have an "alt" attribute, but with a value of undef --
  2681. which is not normally possible).
  2682.  
  2683. Note that when you give several criteria, this is taken to mean you're
  2684. looking for elements that match I<all> your criterion, not just I<any>
  2685. of them.  In other words, there is an implicit "and", not an "or".  So
  2686. if you wanted to express that you wanted to find elements with a
  2687. "name" attribute with the value "foo" I<or> with an "id" attribute
  2688. with the value "baz", you'd have to do it like:
  2689.  
  2690.   @them = $h->look_down(
  2691.     sub {
  2692.       # the lcs are to fold case
  2693.       lc($_[0]->attr('name')) eq 'foo'
  2694.       or lc($_[0]->attr('id')) eq 'baz'
  2695.     }
  2696.   );
  2697.  
  2698. Coderef criteria are more expressive than C<(attr_name, attr_value)>
  2699. criteria, and all C<(attr_name, attr_value)> criteria could be
  2700. expressed in terms of coderefs.  However, C<(attr_name, attr_value)>
  2701. criteria are a convenient shorthand.  (In fact, C<look_down> itself is
  2702. basically "shorthand" too, since anything you can do with C<look_down>
  2703. you could do by traversing the tree, either with the C<traverse>
  2704. method or with a routine of your own.  However, C<look_down> often
  2705. makes for very concise and clear code.)
  2706.  
  2707. =cut
  2708.  
  2709. sub look_down {
  2710.   ref($_[0]) or Carp::croak "look_down works only as an object method";
  2711.  
  2712.   my @criteria;
  2713.   for(my $i = 1; $i < @_;) {
  2714.     Carp::croak "Can't use undef as an attribute name" unless defined $_[$i];
  2715.     if(ref $_[$i]) {
  2716.       Carp::croak "A " . ref($_[$i]) . " value is not a criterion"
  2717.         unless ref $_[$i] eq 'CODE';
  2718.       push @criteria, $_[ $i++ ];
  2719.     } else {
  2720.       Carp::croak "param list to look_down ends in a key!" if $i == $#_;
  2721.       push @criteria, [ scalar($_[0]->_fold_case($_[$i])), 
  2722.                         defined($_[$i+1])
  2723.                           ? ( lc( $_[$i+1] ), ref( $_[$i+1] ) )
  2724.                             # yes, leave that LC!
  2725.                           : undef
  2726.                       ];
  2727.       $i += 2;
  2728.     }
  2729.   }
  2730.   Carp::croak "No criteria?" unless @criteria;
  2731.  
  2732.   my(@pile) = ($_[0]);
  2733.   my(@matching, $val, $this);
  2734.  Node:
  2735.   while(defined($this = shift @pile)) {
  2736.     # Yet another traverser implemented with merely iterative code.
  2737.     foreach my $c (@criteria) {
  2738.       if(ref($c) eq 'CODE') {
  2739.         next Node unless $c->($this);  # jump to the continue block
  2740.       } else { # it's an attr-value pair
  2741.         next Node  # jump to the continue block
  2742.           if # two values are unequal if:
  2743.             (defined($val = $this->{ $c->[0] }))
  2744.               ? (
  2745.                   !defined $c->[1]  # actual is def, critval is undef => fail
  2746.                   or ref $val ne $c->[2]
  2747.                    # have unequal ref values => fail
  2748.                   or lc($val) ne $c->[1]
  2749.                    # have unequal lc string values => fail
  2750.                 )
  2751.               : (defined $c->[1]) # actual is undef, critval is def => fail
  2752.       }
  2753.     }
  2754.     # We make it this far only if all the criteria passed.
  2755.     return $this unless wantarray;
  2756.     push @matching, $this;
  2757.   } continue {
  2758.     unshift @pile, grep ref($_), @{$this->{'_content'} || $nillio};
  2759.   }
  2760.   return @matching if wantarray;
  2761.   return;
  2762. }
  2763.  
  2764.  
  2765. =item $h->look_up( ...criteria... )
  2766.  
  2767. This is identical to $h->look_down, except that whereas $h->look_down
  2768. basically scans over the list:
  2769.  
  2770.    ($h, $h->descendants)
  2771.  
  2772. $h->look_up instead scans over the list
  2773.  
  2774.    ($h, $h->lineage)
  2775.  
  2776. So, for example, this returns all ancestors of $h (possibly including
  2777. $h itself) that are "td" elements with an "align" attribute with a
  2778. value of "right" (or "RIGHT", etc.):
  2779.  
  2780.    $h->look_up("_tag", "td", "align", "right");
  2781.  
  2782. =cut
  2783.  
  2784. sub look_up {
  2785.   ref($_[0]) or Carp::croak "look_up works only as an object method";
  2786.  
  2787.   my @criteria;
  2788.   for(my $i = 1; $i < @_;) {
  2789.     Carp::croak "Can't use undef as an attribute name" unless defined $_[$i];
  2790.     if(ref $_[$i]) {
  2791.       Carp::croak "A " . ref($_[$i]) . " value is not a criterion"
  2792.         unless ref $_[$i] eq 'CODE';
  2793.       push @criteria, $_[ $i++ ];
  2794.     } else {
  2795.       Carp::croak "param list to look_up ends in a key!" if $i == $#_;
  2796.       push @criteria, [ scalar($_[0]->_fold_case($_[$i])),
  2797.                         defined($_[$i+1])
  2798.                           ? ( lc( $_[$i+1] ), ref( $_[$i+1] ) )
  2799.                           : undef  # Yes, leave that LC!
  2800.                       ];
  2801.       $i += 2;
  2802.     }
  2803.   }
  2804.   Carp::croak "No criteria?" unless @criteria;
  2805.  
  2806.   my(@matching, $val);
  2807.   my $this = $_[0];
  2808.  Node:
  2809.   while(1) {
  2810.     # You'll notice that the code here is almost the same as for look_down.
  2811.     foreach my $c (@criteria) {
  2812.       if(ref($c) eq 'CODE') {
  2813.         next Node unless $c->($this);  # jump to the continue block
  2814.       } else { # it's an attr-value pair
  2815.         next Node  # jump to the continue block
  2816.           if # two values are unequal if:
  2817.             (defined($val = $this->{ $c->[0] }))
  2818.               ? (
  2819.                   !defined $c->[1]  # actual is def, critval is undef => fail
  2820.                   or ref $val ne $c->[2]
  2821.                    # have unequal ref values => fail
  2822.                   or lc($val) ne $c->[1]
  2823.                    # have unequal lc string values => fail
  2824.                 )
  2825.               : (defined $c->[1]) # actual is undef, critval is def => fail
  2826.       }
  2827.     }
  2828.     # We make it this far only if all the criteria passed.
  2829.     return $this unless wantarray;
  2830.     push @matching, $this;
  2831.   } continue {
  2832.     last unless defined($this = $this->{'_parent'}) and ref $this;
  2833.   }
  2834.  
  2835.   return @matching if wantarray;
  2836.   return;
  2837. }
  2838.  
  2839. #--------------------------------------------------------------------------
  2840.  
  2841. =item $h->traverse(...options...)
  2842.  
  2843. Lengthy discussion of HTML::Element's unnecessary and confusing
  2844. C<traverse> method has been moved to a separate file:
  2845. L<HTML::Element::traverse>
  2846.  
  2847. =item $h->attr_get_i('attribute')
  2848.  
  2849. In list context, returns a list consisting of the values of the given
  2850. attribute for $self and for all its ancestors starting from $self and
  2851. working its way up.  Nodes with no such attribute are skipped.
  2852. ("attr_get_i" stands for "attribute get, with inheritance".)
  2853. In scalar context, returns the first such value, or undef if none.
  2854.  
  2855. Consider a document consisting of:
  2856.  
  2857.    <html lang='i-klingon'>
  2858.      <head><title>Pati Pata</title></head>
  2859.      <body>
  2860.        <h1 lang='la'>Stuff</h1>
  2861.        <p lang='es-MX' align='center'>
  2862.          Foo bar baz <cite>Quux</cite>.
  2863.        </p>
  2864.        <p>Hooboy.</p>
  2865.      </body>
  2866.    </html>
  2867.  
  2868. If $h is the "cite" element, $h->attr_get_i("lang") in list context
  2869. will return the list ('es-MX', 'i-klingon').  In scalar context, it
  2870. will return the value 'es-MX'.
  2871.  
  2872. If you call with multiple attribute names...
  2873.  
  2874. =item $h->attr_get_i('a1', 'a2', 'a3')
  2875.  
  2876. ...in list context, this will return a list consisting of
  2877. the values of these attributes which exist in $self and its ancestors.
  2878. In scalar context, this returns the first value (i.e., the value of
  2879. the first existing attribute from the first element that has
  2880. any of the attributes listed).  So, in the above example,
  2881.  
  2882.   $h->attr_get_i('lang', 'align');
  2883.  
  2884. will return:
  2885.  
  2886.    ('es-MX', 'center', 'i-klingon') # in list context
  2887.   or
  2888.    'es-MX' # in scalar context.
  2889.  
  2890. But note that this:
  2891.  
  2892.  $h->attr_get_i('align', 'lang');
  2893.  
  2894. will return:
  2895.  
  2896.    ('center', 'es-MX', 'i-klingon') # in list context
  2897.   or
  2898.    'center' # in scalar context.
  2899.  
  2900. =cut
  2901.  
  2902. sub attr_get_i {
  2903.   if(@_ > 2) {
  2904.     my $self = shift;
  2905.     Carp::croak "No attribute names can be undef!"
  2906.      if grep !defined($_), @_;
  2907.     my @attributes = $self->_fold_case(@_);
  2908.     if(wantarray) {
  2909.       my @out;
  2910.       foreach my $x ($self, $self->lineage) {
  2911.         push @out, map { exists($x->{$_}) ? $x->{$_} : () } @attributes;
  2912.       }
  2913.       return @out;
  2914.     } else {
  2915.       foreach my $x ($self, $self->lineage) {
  2916.         foreach my $attribute (@attributes) {
  2917.           return $x->{$attribute} if exists $x->{$attribute}; # found
  2918.         }
  2919.       }
  2920.       return undef; # never found
  2921.     }
  2922.   } else {
  2923.     # Single-attribute search.  Simpler, most common, so optimize
  2924.     #  for the most common case
  2925.     Carp::croak "Attribute name must be a defined value!" unless defined $_[1];
  2926.     my $self = $_[0];
  2927.     my $attribute =  $self->_fold_case($_[1]);
  2928.     if(wantarray) { # list context
  2929.       return
  2930.         map {
  2931.           exists($_->{$attribute}) ? $_->{$attribute} : ()
  2932.         } $self, $self->lineage;
  2933.       ;
  2934.     } else { # scalar context
  2935.       foreach my $x ($self, $self->lineage) {
  2936.         return $x->{$attribute} if exists $x->{$attribute}; # found
  2937.       }
  2938.       return undef; # never found
  2939.     }
  2940.   }
  2941. }
  2942.  
  2943. #--------------------------------------------------------------------------
  2944.  
  2945. =item $h->tagname_map()
  2946.  
  2947. Scans across C<$h> and all its descendants, and makes a hash (a
  2948. reference to which is returned) where each entry consists of a key
  2949. that's a tag name, and a value that's a reference to a list to all
  2950. elements that have that tag name.  I.e., this method returns:
  2951.  
  2952.    {
  2953.      # Across $h and all descendants...
  2954.      'a'   => [ ...list of all 'a'   elements... ],
  2955.      'em'  => [ ...list of all 'em'  elements... ],
  2956.      'img' => [ ...list of all 'img' elements... ],
  2957.    }
  2958.  
  2959. (There are entries in the hash for only those tagnames that occur
  2960. at/under C<$h> -- so if there's no "img" elements, there'll be no
  2961. "img" entry in the hashr(ref) returned.)
  2962.  
  2963. Example usage:
  2964.  
  2965.     my $map_r = $h->tagname_map();
  2966.     my @heading_tags = sort grep m/^h\d$/s, keys %$map_r;
  2967.     if(@heading_tags) {
  2968.       print "Heading levels used: @heading_tags\n";
  2969.     } else {
  2970.       print "No headings.\n"
  2971.     }
  2972.  
  2973. =cut
  2974.  
  2975. sub tagname_map {
  2976.   my(@pile) = $_[0]; # start out the to-do stack for the traverser
  2977.   Carp::croak "find_by_tag_name can be called only as an object method"
  2978.    unless ref $pile[0];
  2979.   my(%map, $this_tag, $this);
  2980.   while(@pile) {
  2981.     $this_tag = ''
  2982.       unless defined(
  2983.        $this_tag = (
  2984.         $this = shift @pile
  2985.        )->{'_tag'}
  2986.       )
  2987.     ; # dance around the strange case of having an undef tagname.
  2988.     push @{ $map{$this_tag} ||= [] }, $this; # add to map
  2989.     unshift @pile, grep ref($_), @{$this->{'_content'} || next}; # traverse
  2990.   }
  2991.   return \%map;
  2992. }
  2993.  
  2994. #--------------------------------------------------------------------------
  2995.  
  2996. =item $h->extract_links() or $h->extract_links(@wantedTypes)
  2997.  
  2998. Returns links found by traversing the element and all of its children
  2999. and looking for attributes (like "href" in an "a" element, or "src" in
  3000. an "img" element) whose values represent links.  The return value is a
  3001. I<reference> to an array.  Each element of the array is reference to
  3002. an array with I<four> items: the link-value, the element that has the
  3003. attribute with that link-value, and the name of that attribute, and
  3004. the tagname of that element.
  3005. (Example: C<['http://www.suck.com/',> I<$elem_obj> C<, 'href', 'a']>.)
  3006. You may or may not end up using the
  3007. element itself -- for some purposes, you may use only the link value.
  3008.  
  3009. You might specify that you want to extract links from just some kinds
  3010. of elements (instead of the default, which is to extract links from
  3011. I<all> the kinds of elements known to have attributes whose values
  3012. represent links).  For instance, if you want to extract links from
  3013. only "a" and "img" elements, you could code it like this:
  3014.  
  3015.   for (@{  $e->extract_links('a', 'img')  }) {
  3016.       my($link, $element, $attr, $tag) = @$_;
  3017.       print
  3018.         "Hey, there's a $tag that links to "
  3019.         $link, ", in its $attr attribute, at ",
  3020.         $element->address(), ".\n";
  3021.   }
  3022.  
  3023. =cut
  3024.  
  3025.  
  3026. sub extract_links
  3027. {
  3028.     my $start = shift;
  3029.  
  3030.     my %wantType;
  3031.     @wantType{$start->_fold_case(@_)} = (1) x @_; # if there were any
  3032.     my $wantType = scalar(@_);
  3033.  
  3034.     my @links;
  3035.  
  3036.     # TODO: add xml:link?
  3037.  
  3038.     my($link_attrs, $tag, $self, $val); # scratch for each iteration
  3039.     $start->traverse(
  3040.       [
  3041.         sub { # pre-order call only
  3042.           $self = $_[0];
  3043.   
  3044.           $tag = $self->{'_tag'};
  3045.           return 1 if $wantType && !$wantType{$tag};  # if we're selective
  3046.   
  3047.           if(defined(  $link_attrs = $HTML::Element::linkElements{$tag}  )) {
  3048.             # If this is a tag that has any link attributes,
  3049.             #  look over possibly present link attributes,
  3050.             #  saving the value, if found.
  3051.             for (ref($link_attrs) ? @$link_attrs : $link_attrs) {
  3052.               if(defined(  $val = $self->attr($_)  )) {
  3053.                 push(@links, [$val, $self, $_, $tag])
  3054.               }
  3055.             }
  3056.           }
  3057.           1; # return true, so we keep recursing
  3058.         },
  3059.         undef
  3060.       ],
  3061.       1, # ignore text nodes
  3062.     );
  3063.     \@links;
  3064. }
  3065.  
  3066. #--------------------------------------------------------------------------
  3067.  
  3068. =item $h->same_as($i)
  3069.  
  3070. Returns true if $h and $i are both elements representing the same tree
  3071. of elements, each with the same tag name, with the same explicit
  3072. attributes (i.e., not counting attributes whose names start with "_"),
  3073. and with the same content (textual, comments, etc.).
  3074.  
  3075. Sameness of descendant elements is tested, recursively, with
  3076. C<$child1-E<gt>same_as($child_2)>, and sameness of text segments is tested
  3077. with C<$segment1 eq $segment2>.
  3078.  
  3079. =cut
  3080.  
  3081. sub same_as {
  3082.   die "same_as() takes only one argument: \$h->same_as(\$i)" unless @_ == 2;
  3083.   my($h,$i) = @_[0,1];
  3084.   die "same_as() can be called only as an object method" unless ref $h;
  3085.  
  3086.   return 0 unless defined $i and ref $i;
  3087.    # An element can't be same_as anything but another element!
  3088.    # They needn't be of the same class, tho.
  3089.  
  3090.   return 1 if $h eq $i;
  3091.    # special (if rare) case: anything is the same as... itself!
  3092.   
  3093.   # assumes that no content lists in/under $h or $i contain subsequent
  3094.   #  text segments, like: ['foo', ' bar']
  3095.   
  3096.   # compare attributes now.
  3097.   #print "Comparing tags of $h and $i...\n";
  3098.  
  3099.   return 0 unless $h->{'_tag'} eq $i->{'_tag'};
  3100.     # only significant attribute whose name starts with "_"
  3101.   
  3102.   #print "Comparing attributes of $h and $i...\n";
  3103.   # Compare attributes, but only the real ones.
  3104.   {
  3105.     # Bear in mind that the average element has very few attributes,
  3106.     #  and that element names are rather short.
  3107.     # (Values are a different story.)
  3108.     
  3109.     my @keys_h = sort grep {length $_ and substr($_,0,1) ne '_'} keys %$h;
  3110.     my @keys_i = sort grep {length $_ and substr($_,0,1) ne '_'} keys %$i;
  3111.     
  3112.     #print '<', join(',', @keys_h), '> =?= <', join(',', @keys_i), ">\n";
  3113.     
  3114.     return 0 unless @keys_h == @keys_i;
  3115.      # different number of real attributes?  they're different.
  3116.     for(my $x = 0; $x < @keys_h; ++$x) {
  3117.       return 0 unless
  3118.        $keys_h[$x] eq $keys_i[$x] and  # same key name
  3119.        $h->{$keys_h[$x]} eq $i->{$keys_h[$x]}; # same value
  3120.        # Should this test for definedness on values?
  3121.        # People shouldn't be putting undef in attribute values, I think.
  3122.     }
  3123.   }
  3124.   
  3125.   #print "Comparing children of $h and $i...\n";
  3126.   my $hcl = $h->{'_content'} || [];
  3127.   my $icl = $i->{'_content'} || [];
  3128.   
  3129.   return 0 unless @$hcl == @$icl;
  3130.    # different numbers of children?  they're different.
  3131.   
  3132.   if(@$hcl) {
  3133.     # compare each of the children:
  3134.     for(my $x = 0; $x < @$hcl; ++$x) {
  3135.       if(ref $hcl->[$x]) {
  3136.         return 0 unless ref($icl->[$x]);
  3137.          # an element can't be the same as a text segment
  3138.         # Both elements:
  3139.         return 0 unless $hcl->[$x]->same_as($icl->[$x]);  # RECURSE!
  3140.       } else {
  3141.         return 0 if ref($icl->[$x]);
  3142.          # a text segment can't be the same as an element
  3143.         # Both text segments:
  3144.         return 0 unless $hcl->[$x] eq $icl->[$x];
  3145.       }
  3146.     }
  3147.   }
  3148.   
  3149.   return 1; # passed all the tests!
  3150. }
  3151.  
  3152.  
  3153. #--------------------------------------------------------------------------
  3154.  
  3155. =item $h = HTML::Element->new_from_lol(ARRAYREF)
  3156.  
  3157. Resursively constructs a tree of nodes, based on the (non-cyclic)
  3158. data structure represented by ARRAYREF, where that is a reference
  3159. to an array of arrays (of arrays (of arrays (etc.))).
  3160.  
  3161. In each arrayref in that structure, different kinds of values are
  3162. treated as follows:
  3163.  
  3164. =over
  3165.  
  3166. =item * Arrayrefs
  3167.  
  3168. Arrayrefs are considered to
  3169. designate a sub-tree representing children for the node constructed
  3170. from the current arrayref.
  3171.  
  3172. =item * Hashrefs
  3173.  
  3174. Hashrefs are considered to contain
  3175. attribute-value pairs to add to the element to be constructed from
  3176. the current arrayref
  3177.  
  3178. =item * Text segments
  3179.  
  3180. Text segments at the start of any arrayref
  3181. will be considered to specify the name of the element to be
  3182. constructed from the current araryref; all other text segments will
  3183. be considered to specify text segments as children for the current
  3184. arrayref.
  3185.  
  3186. =item * Elements
  3187.  
  3188. Existing element objects are either inserted into the treelet
  3189. constructed, or clones of them are.  That is, when the lol-tree is
  3190. being traversed and elements constructed based what's in it, if
  3191. an existing element object is found, if it has no parent, then it is
  3192. added directly to the treelet constructed; but if it has a parent,
  3193. then C<$that_node-E<gt>clone> is added to the treelet at the
  3194. appropriate place.
  3195.  
  3196. =back
  3197.  
  3198. An example will hopefully make this more obvious:
  3199.  
  3200.   my $h = HTML::Element->new_from_lol(
  3201.     ['html',
  3202.       ['head',
  3203.         [ 'title', 'I like stuff!' ],
  3204.       ],
  3205.       ['body',
  3206.         {'lang', 'en-JP', _implicit => 1},
  3207.         'stuff',
  3208.         ['p', 'um, p < 4!', {'class' => 'par123'}],
  3209.         ['div', {foo => 'bar'}, '123'],
  3210.       ]
  3211.     ]
  3212.   );
  3213.   $h->dump;
  3214.  
  3215. Will print this:
  3216.  
  3217.   <html> @0
  3218.     <head> @0.0
  3219.       <title> @0.0.0
  3220.         "I like stuff!"
  3221.     <body lang="en-JP"> @0.1 (IMPLICIT)
  3222.       "stuff"
  3223.       <p class="par123"> @0.1.1
  3224.         "um, p < 4!"
  3225.       <div foo="bar"> @0.1.2
  3226.         "123"
  3227.  
  3228. And printing $h->as_HTML will give something like:
  3229.  
  3230.   <html><head><title>I like stuff!</title></head>
  3231.   <body lang="en-JP">stuff<p class="par123">um, p < 4!
  3232.   <div foo="bar">123</div></body></html>
  3233.  
  3234. You can even do fancy things with C<map>:
  3235.  
  3236.   $body->push_content(
  3237.     # push_content implicitly calls new_from_lol on arrayrefs...
  3238.     ['br'],
  3239.     ['blockquote',
  3240.       ['h2', 'Pictures!'],
  3241.       map ['p', $_],
  3242.       $body2->look_down("_tag", "img"),
  3243.         # images, to be copied from that other tree.
  3244.     ],
  3245.     # and more stuff:
  3246.     ['ul',
  3247.       map ['li', ['a', {'href'=>"$_.png"}, $_ ] ],
  3248.       qw(Peaches Apples Pears Mangos)
  3249.     ],
  3250.   );
  3251.  
  3252. =cut
  3253.  
  3254. sub new_from_lol {
  3255.   my $class = ref($_[0]) || $_[0];
  3256.    # calling as an object method is just the same as ref($h)->new_from_lol(...)
  3257.   my $lol = $_[1];
  3258.  
  3259.   Carp::croak "first argument to new_from_lol mustn't be undef!"
  3260.     unless defined $lol;
  3261.   
  3262.   Carp::croak
  3263.    "first argument to new_from_lol must be an arrayref, not \"$lol\"!"
  3264.     unless ref($lol) eq 'ARRAY';
  3265.  
  3266.   my @ancestor_lols;
  3267.    # So we can make sure there's no cyclicities in this lol.
  3268.    # That would be perverse, but one never knows.
  3269.   my($sub, $k, $v, $node); # last three are scratch values
  3270.   $sub = sub {
  3271.     #print "Building for $_[0]\n";
  3272.     my $lol = $_[0];
  3273.     return unless @$lol;
  3274.     my(@attributes, @children);
  3275.     Carp::croak "Cyclicity detected in source LOL tree, around $lol?!?"
  3276.      if grep($_ eq $lol, @ancestor_lols);
  3277.     push @ancestor_lols, $lol;
  3278.  
  3279.     my $tag_name = 'null';
  3280.  
  3281.     # Recursion in in here:
  3282.     for(my $i = 0; $i < @$lol; ++$i) { # Iterate over children
  3283.       if(ref($lol->[$i]) eq 'ARRAY') { # subtree: most common thing in loltree
  3284.         push @children, $sub->($lol->[$i]);
  3285.       } elsif(! ref($lol->[$i])) {
  3286.         if($i == 0) { # name
  3287.           $tag_name = $lol->[$i];
  3288.         } else { # text segment child
  3289.           push @children, $lol->[$i];
  3290.         }
  3291.       } elsif(ref($lol->[$i]) eq 'HASH') { # attribute hashref
  3292.         keys %{$lol->[$i]}; # reset the each-counter, just in case
  3293.         while(($k,$v) = each %{$lol->[$i]}) {
  3294.           push @attributes, $class->_fold_case($k), $v
  3295.             unless $k eq '_name' or $k eq '_content' or $k eq '_parent';
  3296.           # enforce /some/ sanity!
  3297.         }
  3298.       } elsif(UNIVERSAL::isa($lol->[$i], __PACKAGE__)) {
  3299.         if($lol->[$i]->{'_parent'}) { # if claimed
  3300.           #print "About to clone ", $lol->[$i], "\n";
  3301.           push @children, $lol->[$i]->clone();
  3302.         } else {
  3303.           push @children, $lol->[$i]; # if unclaimed...
  3304.           #print "Claiming ", $lol->[$i], "\n";
  3305.           $lol->[$i]->{'_parent'} = 1; # claim it NOW
  3306.            # This WILL be replaced by the correct value once we actually
  3307.            #  construct the parent, just after the end of this loop...
  3308.         }
  3309.       } else {
  3310.         Carp::croak "new_from_lol doesn't handle references of type "
  3311.           . ref($lol->[$i]);
  3312.       }
  3313.     }
  3314.  
  3315.     pop @ancestor_lols;
  3316.     $node = $class->new($tag_name);
  3317.  
  3318.     #print "Children: @children\n";
  3319.  
  3320.     if($class eq __PACKAGE__) {  # Special-case it, for speed:
  3321.       #print "Special cased / [@attributes]\n";
  3322.       
  3323.       %$node = (%$node, @attributes) if @attributes;
  3324.       #print join(' ', $node, ' ' , map("<$_>", %$node), "\n");
  3325.       if(@children) {
  3326.         $node->{'_content'} = \@children;
  3327.         foreach my $c (@children) { $c->{'_parent'} = $node if ref $c }
  3328.       }
  3329.     } else {  # Do it the clean way...
  3330.       #print "Done neatly\n";
  3331.       while(@attributes) { $node->attr(splice @attributes,0,2) }
  3332.       $node->push_content(@children) if @children;
  3333.     }
  3334.  
  3335.     return $node;
  3336.   };
  3337.  
  3338.   $node = $sub->($lol);
  3339.   undef $sub; # so it won't be in its own frame, so its refcount can hit 0
  3340.   return $node;
  3341. }
  3342.  
  3343. #--------------------------------------------------------------------------
  3344.  
  3345. =item $h->objectify_text()
  3346.  
  3347. This turns any text nodes under $h from mere text segments (strings)
  3348. into real objects, pseudo-elements with a tag-name of "~text", and the
  3349. actual text content in an attribute called "text".  (For a discussion
  3350. of pseudo-elements, see the "tag" method, far above.)  This method is
  3351. provided because, for some purposes, it is convenient or necessary to
  3352. be able, for a given text node, to ask what element is its parent; and
  3353. clearly this is not possible if a node is just a text string.
  3354.  
  3355. Note that these "~text" objects are not recognized as text nodes by
  3356. methods like as_text.  Presumably you will want to call
  3357. $h->objectify_text, perform whatever task that you needed that for,
  3358. and then call $h->deobjectify_text before calling anything like
  3359. $h->as_text.
  3360.  
  3361. This method is experimental, and you are encouraged to report any
  3362. problems you encounter with it.
  3363.  
  3364. =item $h->deobjectify_text()
  3365.  
  3366. This undoes the effect of $h->objectify_text.  That is, it takes any
  3367. "~text" pseudo-elements in the tree at/under $h, and deletes each one,
  3368. replacing each with the content of its "text" attribute. 
  3369.  
  3370. Note that if $h itself is a "~text" pseudo-element, it will be
  3371. destroyed -- a condition you may need to treat specially in your
  3372. calling code (since it means you can't very well do anything with $h
  3373. after that).  So that you can detect that condition, if $h is itself a
  3374. "~text" pseudo-element, then this method returns the value of the
  3375. "text" attribute, which should be a defined value; in all other cases,
  3376. it returns undef.
  3377.  
  3378. This method is experimental, and you are encouraged to report any
  3379. problems you encounter with it.
  3380.  
  3381. (This method assumes that no "~text" pseudo-element has any children.)
  3382.  
  3383. =cut
  3384.  
  3385. sub objectify_text {
  3386.   my(@stack) = ($_[0]);
  3387.  
  3388.   my($this);
  3389.   while(@stack) {
  3390.     foreach my $c (@{( $this = shift @stack )->{'_content'}}) {
  3391.       if(ref($c)) {
  3392.         unshift @stack, $c;  # visit it later.
  3393.       } else {
  3394.         $c = ( $this->{'_element_class'} || __PACKAGE__
  3395.              )->new('~text', 'text' => $c, '_parent' => $this);
  3396.       }
  3397.     }
  3398.   }
  3399.   return;
  3400. }
  3401.  
  3402. sub deobjectify_text {
  3403.   my(@stack) = ($_[0]);
  3404.   my($old_node);
  3405.  
  3406.   if( $_[0]{'_tag'} eq '~text') { # special case
  3407.     # Puts the $old_node variable to a different purpose
  3408.     if($_[0]{'_parent'}) {
  3409.       $_[0]->replace_with( $old_node = delete $_[0]{'text'} )->delete;
  3410.     } else {  # well, that's that, then!
  3411.       $old_node = delete $_[0]{'text'};
  3412.     }
  3413.  
  3414.     if(ref($_[0]) eq __PACKAGE__) { # common case
  3415.       %{$_[0]} = ();  # poof!
  3416.     } else {
  3417.       # play nice:
  3418.       delete $_[0]{'_parent'};
  3419.       $_[0]->delete;
  3420.     }
  3421.     return '' unless defined $old_node; # sanity!
  3422.     return $old_node;
  3423.   }
  3424.  
  3425.   while(@stack) {
  3426.     foreach my $c (@{(shift @stack)->{'_content'}}) {
  3427.       if(ref($c)) {
  3428.         if($c->{'_tag'} eq '~text') {
  3429.           $c = ($old_node = $c)->{'text'};
  3430.       if(ref($old_node) eq __PACKAGE__) { # common case
  3431.             %$old_node = ();  # poof!
  3432.           } else {
  3433.             # play nice:
  3434.             delete $old_node->{'_parent'};
  3435.             $old_node->delete;
  3436.           }
  3437.         } else {
  3438.           unshift @stack, $c;  # visit it later.
  3439.         }
  3440.       }
  3441.     }
  3442.   }
  3443.  
  3444.   return undef;
  3445. }
  3446.  
  3447. #--------------------------------------------------------------------------
  3448.  
  3449. =item $h->number_lists()
  3450.  
  3451. For every UL, OL, DIR, and MENU element at/under $h, this sets a
  3452. "_bullet" attribute for every child LI element.  For LI children of an
  3453. OL, the "_bullet" attribute's value will be something like "4.", "d.",
  3454. "D.", "IV.", or "iv.", depending on the OL element's "type" attribute.
  3455. LI children of a UL, DIR, or MENU get their "_bullet" attribute set
  3456. to "*".  
  3457. There should be no other LIs (i.e., except as children of OL, UL, DIR,
  3458. or MENU elements), and if there are, they are unaffected.
  3459.  
  3460. =cut
  3461.  
  3462. {
  3463.   # The next three subs are basically copied from my module Number::Latin,
  3464.   #  based on a one-liner by Abigail.  Yes, I could simply require that
  3465.   #  module, and a roman numeral module too, but really, HTML-Tree already
  3466.   #  has enough dependecies as it is; and anyhow, I don't need the functions
  3467.   #  that do latin2int or roman2int.
  3468.  
  3469.   sub _int2latin {
  3470.     return undef unless defined $_[0];
  3471.     return '0' if $_[0] < 1 and $_[0] > -1;
  3472.     return '-' . _i2l( abs int $_[0] ) if $_[0] <= -1; # tolerate negatives
  3473.     return       _i2l(     int $_[0] );
  3474.   }
  3475.  
  3476.   sub _int2LATIN {
  3477.     # just the above plus uc
  3478.     return undef unless defined $_[0];
  3479.     return '0' if $_[0] < 1 and $_[0] > -1;
  3480.     return '-' . uc(_i2l( abs int $_[0] )) if $_[0] <= -1;  # tolerate negs
  3481.     return       uc(_i2l(     int $_[0] ));
  3482.   }
  3483.  
  3484.   my @alpha = ('', 'a' .. 'z'); 
  3485.  
  3486.   sub _i2l { # the real work
  3487.     my $int = $_[0] || return "";
  3488.     _i2l(int (($int - 1) / 26)) . $alpha[$int % 26];  # yes, recursive
  3489.   }
  3490. }
  3491.  
  3492. {
  3493.   # And now, some much less impressive Roman numerals code:
  3494.  
  3495.   my(@i) = ('', qw(I II III IV V VI VII VIII IX));
  3496.   my(@x) = ('', qw(X XX XXX XL L LX LXX LXXX XC));
  3497.   my(@c) = ('', qw(C CC CCC CD D DC DCC DCCC CM));
  3498.   my(@m) = ('', qw(M MM MMM));
  3499.  
  3500.   sub _int2ROMAN {
  3501.     my($i, $pref);
  3502.     return '0' if 0 == ($i = int($_[0] || 0)); # zero is a special case
  3503.     return $i + 0 if $i <= -4000 or $i >= 4000;
  3504.     # Because over 3999 would require non-ASCII chars, like D-with-)-inside
  3505.     if($i < 0) { # grumble grumble tolerate negatives grumble
  3506.       $pref = '-'; $i = abs($i);
  3507.     } else {
  3508.       $pref = '';  # normal case
  3509.     }
  3510.  
  3511.     my($x,$c,$m) = (0,0,0);
  3512.     if(     $i >= 10) { $x = $i / 10; $i %= 10;
  3513.       if(   $x >= 10) { $c = $x / 10; $x %= 10;
  3514.         if( $c >= 10) { $m = $c / 10; $c %= 10; } } }
  3515.     #print "m$m c$c x$x i$i\n";
  3516.  
  3517.     return join('', $pref, $m[$m], $c[$c], $x[$x], $i[$i] );
  3518.   }
  3519.  
  3520.   sub _int2roman { lc(_int2ROMAN($_[0])) }
  3521. }
  3522.  
  3523. sub _int2int { $_[0] } # dummy
  3524.  
  3525. %list_type_to_sub = (
  3526.   'I' => \&_int2ROMAN,  'i' => \&_int2roman,
  3527.   'A' => \&_int2LATIN,  'a' => \&_int2latin,
  3528.   '1' => \&_int2int,
  3529. );
  3530.  
  3531. sub number_lists {
  3532.   my(@stack) = ($_[0]);
  3533.   my($this, $tag, $counter, $numberer); # scratch
  3534.   while(@stack) { # yup, pre-order-traverser idiom
  3535.     if(($tag = ($this = shift @stack)->{'_tag'}) eq 'ol') {
  3536.       # Prep some things:
  3537.       $counter = (($this->{'start'} || '') =~ m<^\s*(\d{1,7})\s*$>s) ? $1 : 1;
  3538.       $numberer = $list_type_to_sub{ $this->{'type'} }
  3539.                || $list_type_to_sub{'1'};
  3540.  
  3541.       # Immeditately iterate over all children
  3542.       foreach my $c (@{ $this->{'_content'} || next}) {
  3543.     next unless ref $c;
  3544.     unshift @stack, $c;
  3545.     if($c->{'_tag'} eq 'li') {
  3546.       $counter = $1 if(($c->{'value'} || '') =~ m<^\s*(\d{1,7})\s*$>s);
  3547.       $c->{'_bullet'} = $numberer->($counter) . '.';
  3548.       ++$counter;
  3549.     }
  3550.       }
  3551.  
  3552.     } elsif($tag eq 'ul' or $tag eq 'dir' or $tag eq 'menu') {
  3553.       # Immeditately iterate over all children
  3554.       foreach my $c (@{ $this->{'_content'} || next}) {
  3555.     next unless ref $c;
  3556.     unshift @stack, $c;
  3557.     $c->{'_bullet'} = '*' if $c->{'_tag'} eq 'li';
  3558.       }
  3559.  
  3560.     } else {
  3561.       foreach my $c (@{ $this->{'_content'} || next}) {
  3562.     unshift @stack, $c if ref $c;
  3563.       }
  3564.     }
  3565.   }
  3566.   return;
  3567. }
  3568.  
  3569.  
  3570. #--------------------------------------------------------------------------
  3571.  
  3572. =item $h->has_insane_linkage
  3573.  
  3574. This method is for testing whether this element or the elements
  3575. under it have linkage attributes (_parent and _content) whose values
  3576. are deeply aberrant: if there are undefs in a content list; if an
  3577. element appears in the content lists of more than one element;
  3578. if the _parent attribute of an element doesn't match its actual
  3579. parent; or if an element appears as its own descendant (i.e.,
  3580. if there is a cyclicity in the tree).
  3581.  
  3582. This returns empty list (or false, in scalar context) if the subtree's
  3583. linkage methods are sane; otherwise it returns two items (or true, in
  3584. scalar context): the element where the error occurred, and a string
  3585. describing the error.
  3586.  
  3587. This method is provided is mainly for debugging and troubleshooting --
  3588. it should be I<quite impossible> for any document constructed via
  3589. HTML::TreeBuilder to parse into a non-sane tree (since it's not
  3590. the content of the tree per se that's in question, but whether
  3591. the tree in memory was properly constructed); and it I<should> be
  3592. impossible for you to produce an insane tree just thru reasonable
  3593. use of normal documented structure-modifying methods.  But if you're
  3594. constructing your own trees, and your program is going into infinite
  3595. loops as during calls to traverse() or any of the secondary
  3596. structural methods, as part of debugging, consider calling is_insane
  3597. on the tree.
  3598.  
  3599. =cut
  3600.  
  3601. sub has_insane_linkage {
  3602.   my @pile = ($_[0]);
  3603.   my($c, $i, $p, $this); # scratch
  3604.   
  3605.   # Another iterative traverser; this time much simpler because
  3606.   #  only in pre-order:
  3607.   my %parent_of = ($_[0], 'TOP-OF-SCAN');
  3608.   while(@pile) {
  3609.     $this = shift @pile;
  3610.     $c = $this->{'_content'} || next;
  3611.     return($this, "_content attribute is true but nonref.")
  3612.      unless ref($c) eq 'ARRAY';
  3613.     next unless @$c;
  3614.     for($i = 0; $i < @$c; ++$i) {
  3615.       return($this, "Child $i is undef")
  3616.        unless defined $c->[$i];
  3617.       if(ref($c->[$i])) {
  3618.         return($c->[$i], "appears in its own content list")
  3619.          if $c->[$i] eq $this;
  3620.         return($c->[$i],
  3621.           "appears twice in the tree: once under $this, once under $parent_of{$c->[$i]}"
  3622.         )
  3623.          if exists $parent_of{$c->[$i]};
  3624.         $parent_of{$c->[$i]} = ''.$this;
  3625.           # might as well just use the stringification of it.
  3626.         
  3627.         return($c->[$i], "_parent attribute is wrong (not defined)")
  3628.          unless defined($p = $c->[$i]{'_parent'});
  3629.         return($c->[$i], "_parent attribute is wrong (nonref)")
  3630.          unless ref($p);
  3631.         return($c->[$i],
  3632.           "_parent attribute is wrong (is $p; should be $this)"
  3633.         )
  3634.          unless $p eq $this;
  3635.       }
  3636.     }
  3637.     unshift @pile, grep ref($_), @$c;
  3638.      # queue up more things on the pile stack
  3639.   }
  3640.   return; #okay
  3641. }
  3642.  
  3643. #==========================================================================
  3644.  
  3645. sub _asserts_fail {  # to be run on trusted documents only
  3646.   my(@pile) = ($_[0]);
  3647.   my(@errors, $this, $id, $assert, $parent, $rv);
  3648.   while(@pile) {
  3649.     $this = shift @pile;
  3650.     if(defined($assert = $this->{'assert'})) {
  3651.       $id = ($this->{'id'} ||= $this->address); # don't use '0' as an ID, okay?
  3652.       unless(ref($assert)) {
  3653.         package main;
  3654.         $assert = $this->{'assert'} = (
  3655.           $assert =~ m/\bsub\b/ ? eval($assert) : eval("sub {  $assert\n}")
  3656.         );
  3657.         if($@) {
  3658.           push @errors, [$this, "assertion at $id broke in eval: $@"];
  3659.           $assert = $this->{'assert'} = sub {};
  3660.         }
  3661.       }
  3662.       $parent = $this->{'_parent'};
  3663.       $rv = undef;
  3664.       eval {
  3665.         $rv =
  3666.          $assert->(
  3667.            $this, $this->{'_tag'}, $this->{'_id'}, # 0,1,2
  3668.            $parent ? ($parent, $parent->{'_tag'}, $parent->{'id'}) : () # 3,4,5
  3669.          )
  3670.       };
  3671.       if($@) {
  3672.         push @errors, [$this, "assertion at $id died: $@"];
  3673.       } elsif(!$rv) {
  3674.         push @errors, [$this, "assertion at $id failed"]
  3675.       }
  3676.        # else OK
  3677.     }
  3678.     push @pile, grep ref($_), @{$this->{'_content'} || next};
  3679.   }
  3680.   return @errors;
  3681. }
  3682.  
  3683.  
  3684. #==========================================================================
  3685. 1;
  3686.  
  3687. __END__
  3688.  
  3689. =back
  3690.  
  3691. =head1 BUGS
  3692.  
  3693. * If you want to free the memory associated with a tree built of
  3694. HTML::Element nodes, then you will have to delete it explicitly.
  3695. See the $h->delete method, above.
  3696.  
  3697. * There's almost nothing to stop you from making a "tree" with
  3698. cyclicities (loops) in it, which could, for example, make the
  3699. traverse method go into an infinite loop.  So don't make
  3700. cyclicities!  (If all you're doing is parsing HTML files,
  3701. and looking at the resulting trees, this will never be a problem
  3702. for you.)
  3703.  
  3704. * There's no way to represent comments or processing directives
  3705. in a tree with HTML::Elements.  Not yet, at least.
  3706.  
  3707. * There's (currently) nothing to stop you from using an undefined
  3708. value as a text segment.  If you're running under C<perl -w>, however,
  3709. this may make HTML::Element's code produce a slew of warnings.
  3710.  
  3711. =head1 NOTES ON SUBCLASSING
  3712.  
  3713. You are welcome to derive subclasses from HTML::Element, but you
  3714. should be aware that the code in HTML::Element makes certain
  3715. assumptions about elements (and I'm using "element" to mean ONLY an
  3716. object of class HTML::Element, or of a subclass of HTML::Element):
  3717.  
  3718. * The value of an element's _parent attribute must either be undef or
  3719. otherwise false, or must be an element.
  3720.  
  3721. * The value of an element's _content attribute must either be undef or
  3722. otherwise false, or a reference to an (unblessed) array.  The array
  3723. may be empty; but if it has items, they must ALL be either mere
  3724. strings (text segments), or elements.
  3725.  
  3726. * The value of an element's _tag attribute should, at least, be a 
  3727. string of printable characters.
  3728.  
  3729. Moreover, bear these rules in mind:
  3730.  
  3731. * Do not break encapsulation on objects.  That is, access their
  3732. contents only thru $obj->attr or more specific methods.
  3733.  
  3734. * You should think twice before completely overriding any of the
  3735. methods that HTML::Element provides.  (Overriding with a method that
  3736. calls the superclass method is not so bad, tho.)
  3737.  
  3738. =head1 SEE ALSO
  3739.  
  3740. L<HTML::Tree>; L<HTML::TreeBuilder>; L<HTML::AsSubs>; L<HTML::Tagset>; 
  3741. and, for the morbidly curious, L<HTML::Element::traverse>.
  3742.  
  3743. =head1 COPYRIGHT
  3744.  
  3745. Copyright 1995-1998 Gisle Aas, 1999-2001 Sean M. Burke.
  3746.  
  3747. This library is free software; you can redistribute it and/or
  3748. modify it under the same terms as Perl itself.
  3749.  
  3750. This program is distributed in the hope that it will be useful, but
  3751. without any warranty; without even the implied warranty of
  3752. merchantability or fitness for a particular purpose.
  3753.  
  3754. =head1 AUTHOR
  3755.  
  3756. Original author Gisle Aas E<lt>gisle@aas.noE<gt>; current maintainer
  3757. Sean M. Burke, E<lt>sburke@cpan.orgE<gt>
  3758.  
  3759. =cut
  3760.  
  3761. If you've read the code this far, you need some hummus:
  3762.  
  3763. EASY HUMMUS
  3764. (Adapted from a recipe by Ralph Baccash (1937-2000))
  3765.  
  3766. INGREDIENTS:
  3767.  
  3768.   - The juice of two smallish lemons
  3769.      (adjust to taste, and depending on how juicy the lemons are)
  3770.   - 6 tablespoons of tahini
  3771.   - 4 tablespoons of olive oil
  3772.   - 5 big cloves of garlic, chopped fine
  3773.   - salt to taste
  3774.   - pepper to taste
  3775.   - onion powder to taste
  3776.   - pinch of coriander powder  (optional)
  3777.   - big pinch of cumin
  3778. Then:
  3779.   - 2 16oz cans of garbanzo beans
  3780.   - parsley, or Italian parsley
  3781.   - a bit more olive oil
  3782.  
  3783. PREPARATION:
  3784.  
  3785. Drain one of the cans of garbanzos, discarding the juice.  Drain the
  3786. other, reserving the juice.
  3787.  
  3788. Peel the garbanzos (just pressing on each a bit until the skin slides
  3789. off).  It will take time to peel all the garbanzos.  It's optional, but
  3790. it makes for a smoother hummus.  Incidentally, peeling seems much
  3791. faster and easier if done underwater -- i.e., if the beans are in a
  3792. bowl under an inch or so of water.
  3793.  
  3794. Now, in a blender, combine everything in the above list, starting at the
  3795. top, stopping at (but including) the cumin.  Add one-third of the can's
  3796. worth of the juice that you reserved.  Blend very well.  (For lack of a
  3797. blender, I've done okay using a Braun hand-mixer.)
  3798.  
  3799. Start adding the beans little by little, and keep blending, and
  3800. increasing speeds until very smooth.  If you want to make the mix less
  3801. viscous, add more of the reserved juice.  Adjust the seasoning as
  3802. needed.
  3803.  
  3804. Cover with chopped parsley, and a thin layer of olive oil.  The parsley
  3805. is more or less optional, but the olive oil is necessary, to keep the
  3806. hummus from discoloring.  Possibly sprinkle with paprika or red chile
  3807. flakes.
  3808.  
  3809. Serve at about room temperature, with warm pitas.  Possible garnishes
  3810. include olives, peperoncini, tomato wedges.
  3811.  
  3812. Variations on this recipe consist of adding or substituting other
  3813. spices.  The garbanzos, tahini, lemon juice, and oil are the only really
  3814. core ingredients, and note that their quantities are approximate.
  3815.  
  3816. For more good recipes along these lines, see:
  3817.   Karaoglan, Aida.  1992.  /Food for the Vegetarian/.  Interlink Books,
  3818.   New York.  ISBN 1-56656-105-1.
  3819.   http://www.amazon.com/exec/obidos/ASIN/1566561051/
  3820.  
  3821. # End
  3822.